1、首先创建一个文件夹
如ng2_deco
2、cmd 进入ng2_deco中 执行命令 npm init,会在ng2_dec目录下生成package.json
3、配置package.json文件,内容如下
{
"name": "ng2_deco",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.publish.config.js",
"start": "webpack-dev-server --config webpack.dev.config.js --devtool -eval --progress --color --hot --content-base src"
},
"author": "",
"license": "ISC",
"devDependencies": {
"awesome-typescript-loader": "^3.2.1",
"webpack": "^3.0.0",
"webpack-dev-server": "^2.5.0"
},
"dependencies": {
"reflect-metadata": "^0.1.10",
"tslint": "^3.15.1",
"typescript": "~2.2.0"
}
}
4、创建tsconfig.json文件,配置内容如下
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015","dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"typeRoots": [ "node_modules/@types/" ]
},
"exclude": [ "node_modules" ]
}
5、创建webpack.dev.config.js文件,内容如下
let webpack = require('webpack');
let path = require('path');
module.exports = {
entry: path.resolve(__dirname,'./index.ts'),
output:{
path:path.resolve(__dirname, 'dist'),
filename:'index.js'
},
resolve: {
extensions: ['.js','.ts']
},
module:{
rules: [
{
test:/\.js?$/,
loaders: [
{
loader: 'awesome-typescript-loader',
options: {configFileName:path.resolve(__dirname) + '/tsconfig.json'}
}
]
}
]
},
plugins: [
new webpack.NodeEnvironmentPlugin(),
]
};
6、在cmd进入ng2_deco目录下 执行 npm install,会生成node_modules目录
7、再次执行 npm install webpack --save-dev,到此 安装完毕
8、方法装饰器
1)创建html、ts文件
<html>
<head>
<title>装饰器</title>
<script src="index.js"></script>
</head>
<body>
</body>
</html>
function methodDec(){
return function(){
console.log("bbb");
}
}
class Test{
@methodDec()
method(){
}
}
2)使用tsc编译ts文件
发现报错 没有关系,打开浏览器,访问文件
9、类加载器
function classDec< T extends {new(...args:any[]):{}}>(constructor:T){
return class extends constructor{
a = "aa";
b = "bb";
}
}
@classDec
class Test{
name:string;
constructor(name:string){
this.name = name;
}
}
console.log(new Test("ng2"));
注意:类中是不能改变修饰器中的值的
将代码修改为
function classDec< T extends {new(...args:any[]):{}}>(constructor:T){
return class extends constructor{
a = "aa";
b = "bb";
}
}
@classDec
class Test{
name:string;
a:string;
constructor(name:string,a:string){
this.name = name;
this.a = a;
}
}
console.log(new Test("ng2","no"));
发现a的结果还是aa而不是no。