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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值