webpack项目使用typescript小记

4,054 阅读1分钟

我对你的思念

像野草般生长

铺满了我的脑海

我的心间

我和你之间的每一米距离

安装typescript

npm install typescript ts-loader -D

初始化tsconfig配置文件

tsc --init

在项目根目录下生成tsconfig.json配置文件

项目改造

  1. 在webpack.config.js中添加ts-loader,修改main.js为main.ts
module: {
	rules: [
    	{
        	test: /\.ts$/,
            use: 'ts-loader',
            exclude: /(node_modules)/,
        }
    ]
}
  1. 修改tsconfig.json配置文件
{
	"files": ["./config/index.ts"],/*指定编译文件,指定一个包含相对或绝对文件路径的列表*/
    "include": ["./src/main/*.ts"],/*指定编译文件,属性指定一个文件glob匹配模式列表*/
    "exclude": ["node_modules"],/*指定不编译文件,属性指定一个文件glob匹配模式列表*/
    "compilerOptions": {
    	"target": "es5",
    	"module": "es6",
        "allowJs": true,
        "outDir": "./dist"
    }
}
  1. 别名修改

项目中为了方便引用添加了别名,需要在tsconfig.json中添加相应配置,要不然报错

webpack.config.js

alias: {
            '@service': path.resolve(__dirname, './../../../service'),
            '@CONFIG': path.resolve(__dirname, `./config/${NODE_ENV}.json`),
        },

tsconfig.json

"compilerOptions": {
	"baseUrl": "./",
    "paths": {
      "@service/*": ["foundation/native/service"],
      "@CONFIG/*": ["config/*"],
    },   
}

baseUrl和paths需要搭配使用,这里@CONFIG配置是无效的,因为webpack中使用了环境变量动态获取变量配置,tsconfig.json不知道怎么做,就变通了一下,在config文件夹中添加index.ts文件进行配置输出。

config/index.ts

import development from './development.json';
import production from './production.json';

interface config {
    '***': string,
    '***': string,
    '***': string
}

const config:config = process.env.NODE_ENV === 'production'? production: development;

export default config;

这里ts文件中引用了json文件,typescript会报错,需要在'compilerOptions'中添点配置

tsconfig.js

"moduleResolution": "node",
"resolveJsonModule": true,

相应的webpack.config.js和main.ts中的引用方式也要改下

webpack.config.js

alias: {
            '@CONFIG': path.resolve(__dirname, `./config`),
        }

main.ts

// import CONFIG from '@CONFIG';
// 改为
import CONFIG from '@CONFIG/index';

关于别名这块还有两种解决方法,一个是使用tsconfig-paths-webpack-plugin插件,该插件可以自动copy tsconfig中的paths到webpack.resolve.alias,另一个是使用自定义webpack插件,实现将tsconfig中的路径映射copy到webpack.resolve.alias中,我这里别名少,图省事,就不折腾了。

上面代码中引用的ts文件会报错Can't resolve 'xxxx' in 'xxxx',找不到文件,改成@CONFIG/index.ts,添加.ts后缀,webpack又报错'导入路径不能以“.ts”扩展名结束。考虑改为导入xxxx',我去。。。

修复方法:在resolve中添加后缀支持

webpack.config.js

resolve: {
        alias: {
            
        },
        extensions: ['.ts', '.js']
}

$(this)问题

function getMoreTabData() {
    let $this:any = null;
    if ($(this).hasClass('seeMoreBtn')) {
        $this = $(this);
    } else {
        $this = $(this).parent('.loadMoreErr').siblings('.seeMoreBtn');
        $this.hide().siblings('.loadMoreErr').css({'display': 'none'});
    }
}

报错如下:

修改方法:

function getMoreTabData(event:any) {
    let $this:any = null;
    if ($(event.target).hasClass('seeMoreBtn')) {
        $this = $(event.target);
    } else {
        $this = $(event.target).parent('.loadMoreErr').siblings('.seeMoreBtn');
        $this.hide().siblings('.loadMoreErr').css({'display': 'none'});
    }