TypeScript整合Webpack开发工程

1、初始化项目

首先在合适的目录下创建ts-webpack文件夹,然后在该文件夹所在的目录下执行npm的初始化命令,即:

1
npm init

然后根据提示的输入相应的信息即可,如果图简单,一直按回车键即可。

2、新增基本依赖包

初始化好项目后,紧接着添加TypeScript与Webpack整合的基本依赖包ts-loader, typescript, webpack, webpack-cli,即输入命令:

1
npm install ts-loader, typescript, webpack, webpack-cli

3、新增tsconfig.json配置文件

tsconfig.json配置,可以通过tsc命令生成,即在工程目录下输入如下命令:

1
tsc --init

则在工程目录下会有tsconfig.json文件,文件内容为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */

/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}

可以根据具体情况调整相应的参数,在这就保持默认配置。

4、新增webpack.config.js配置文件

首先在工程目录下新建一个src文件夹,用于存放TypeScript相关源代码的,先在src文件夹中新建index.ts文件,用于工程的入口文件。

在工程目录下新建webpack.config.js配置文件,并加入基本配置,即:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const path = require('path');

module.exports = {
// 入口文件
entry: "./src/index.ts",

// 指定打包文件所在目录
output: {
// 打包文件目录
path: path.resolve(__dirname, "dist"),
// 打包文件名
filename: "bundle.js",
},

// 设置mode模式, development:开发环境,production:生产环境
mode: "production",

// 指定打包的模块
module: {
// 指定加载规则
rules: [
{
// 指定规则生效的文件
test: /\.ts$/,
use: "ts-loader",
// 要排除的文件
exclude: /node_modules/
}
]
}
}

在package.json文件中的scripts中加入打包命令,即:

1
2
3
4
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
}

到目前为止,本工程已经将TypeScript和Webpack做了基本整合了,可以测试一下,首先在入口文件index.ts中加入一个ts测试代码,即:

1
2
3
4
5
function sum(num1:number, num2:number):number {
return num1 + num2;
}

console.log(sum(10, 20));

然后输入打包命令,即:

1
npm run build

可以发现在工程目录下多了一个dist文件夹,里面有bundle.js文件。

5、引入html-webpack-plugin、clean-webpack-plugin和webpack-dev-server

目前工程虽然可以正常打包将ts转换成js,但是要验证js的效果却比较麻烦,还需要手动创建html文件,然后将打包生成的js文件引入测试。

可以通过html-webpack-plugin插件,可以自动的将html模板文件中引入打包后js文件,即首先添加依赖:

1
npm install html-webpack-plugin

然后在webpack.config.js配置文件中首先引入这个插件,即:

1
2
// 引入html插件
const HTMLWebpackPlugin = require('html-webpack-plugin');

然后新增plugins配置,即:

1
2
3
4
5
6
// 配置插件
plugins: [
new HTMLWebpackPlugin({
template: "./src/index.html"
}),
]

其中index.html就是模板文件,打包后会自动将js文件引入到该文件中。

同时为了能够自动运行工程,可以通过webpack-dev-server实现,首先添加依赖:

1
npm install webpack-dev-server

然后在package.json文件中加入启动命令,即在scripts配置中加入:

1
"start": "webpack serve --open chrome.exe"

即运行命令:

1
npm run start

时,会自动打开chrome浏览器,然后加载index.html与js整合后的文件,这样就可以看到开发的效果了,同时还是支持执行部署的,即修改了ts文件后,会自动在浏览器中有效果。

为了防止打包过程中出现缓存导致的问题,可以通过clean-webpack-plugin插件解决,先添加依赖后,然后在webpack.config.js配置文件中引入该插件,即:

1
2
// 引入clean插件
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

然后在plugins配置加入,即:

1
2
3
4
5
6
7
8
9
// 配置插件
plugins: [
// 清除缓存
new CleanWebpackPlugin(),

new HTMLWebpackPlugin({
template: "./src/index.html"
}),
],

6、整合babel

为了ts转换的js兼容各种浏览器,则整合babel,首先添加相应的依赖,即:

1
npm install @babel/core, @babel/preset-env, babel-loader, core-js

然后修改webpack.config.js配置文件,即修改use配置项,即改成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use: [
// 配置babel
{
// 指定加载器
loader: "babel-loader",
// 设置babel
options: {
// 设置预定义环境
presets: [
[
// 指定环境的插件
"@babel/preset-env",
// 配置信息
{
// 需要兼容的目标浏览器
targets: {
"chrome": "88",
"ie": "11"
},
"corejs": "3",
// 使用corejs的方式,按需加载
"useBuiltIns": "usage"
}
]
]
}
},

"ts-loader"
]

其中各个配置项上方都有相应的说明。

至此TypeScript与Webpack就整合完成了,完整项目在Github中,即:https://github.com/lzj09/ts-webpack

作者

lzj09

发布于

2021-05-30

更新于

2021-05-31

许可协议

评论