Angularjs的项目一般用js比较多,使用的是js + less/css + html模式,那么如何将这里的js转换为ts写法,使之能够支持es5 & es6语法,支持强类型语法提示及提高开发效率、容错等。下面一一道来:
1. 首先在项目根目录添加一个tsconfig.json文件,这个文件即为ts的配置文件,然后npm按照typescript及相关@type类型定义。
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
2. 我们如果用的是gulp + webpack打包,那么需要增加一个ts-loader,这里截取了部分webpack的配置,具体项目自己修改。
module: {
preLoaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
}],
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['ng-annotate', 'babel-loader']
}, {
test: /\.ts$/,
exclude: /node_modules/,
loader: 'ts-loader'
}]
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '']
},
3. 检查package.json文件是否已安装typescript、ts-loader、@types/angular模块。
4. 更改文件扩展名js到ts,然后文件中的所有ts报错全部改掉,基本上只是一些类型定义,可以暂时以any代替,后续逐步改为强类型。
5. 这时候可以运行gulp serve,然后会报一个类似services inject的错误,这个时候需要在construct头部注入service:
static $inject = ['$scope', '$log', '$state', '$timeout', '$interval', 'toastr', 'checkCaptcha', 'refreshCaptchaUrl', 'loginService',
'psdJsencryptService', 'queryString', 'notifyingService', 'publicService', 'authAppModal', 'verifyCaptcha', '$stateParams'];
constructor($scope: any, $log: any, $state: any, $timeout: any, $interval: any, toastr: any, checkCaptcha: any, refreshCaptchaUrl: any,
loginService: any, psdJsencryptService: any, queryString: any, notifyingService: any, publicService: any, authAppModal: any,
verifyCaptcha: any, $stateParams: any) {
6. 再次运行gulp serve,完美运行成功;