700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 【Angularjs系列】Angularjs项目中切换js到ts(上)

【Angularjs系列】Angularjs项目中切换js到ts(上)

时间:2021-01-30 21:21:45

相关推荐

【Angularjs系列】Angularjs项目中切换js到ts(上)

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": ["es", "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,完美运行成功;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。