发布于 

ts+webpack环境构建

npm包初始化和安装typescript

将ts_demo文件夹初始化为一个npm包

1
npm init

全局安装typescript

1
cnpm i typescript -g

如果出现以下错误

1
C:\Users\xxx\AppData\Roaming\npm\cnpm.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅

用管理员身份运行power shell,执行以下操作,根据提示输入A回车即可

1
set-ExecutionPolicy RemoteSigned

ts初始化:tsc --init 会生成tsconfig.json文件

新建文件夹src,在src下新建index.ts

配置构建工具webpack

安装webpack相关依赖(在ts_demo目录下安装)

1
cnpm i webpack webpack-cli webpack-dev-server -D

创建build目录(存放所有配置文件)

webpack.config.js 是所有文件的入口
webpack.bash.config.js 公共环境的配置
webpack.dev.config.js 开发环境的配置
webpack.pro.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
//base.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
entry: "./src/index.ts",
output: {
filename: 'app.js'
},
resolve: {
extensions: [ '.js', '.ts', '.tsx' ]
},
module: {
rules: [
{
test: /\.tsx?$/i,
use: [{
loader: 'ts-loader'
}],
exclude: /node_modules/
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/tpl/index.html'
})
]
}
1
2
3
4
5
6
7
8
9
10
//webpack.config.js
const {merge} = require('webpack-merge')
const baseConfig = require('./webpack.base.config')
const devConfig = require('./webpack.dev.config')
const proConfig = require('./webpack.pro.config')

module.exports = (env,argv) => {
let config = argv.mode === 'development' ? devConfig : proConfig;
return merge(baseConfig,config)
}
1
2
3
4
//dev.config.js
module.exports = {
devtool: 'source-map'
}
1
2
3
4
5
6
7
8
//pro.config.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
plugins: [
new CleanWebpackPlugin()
]
}

安装ts-loader(在ts_demo目录下安装)

1
cnpm i ts-loader typescript -D

安装模板生成文件(在ts_demo目录下安装)

1
cnpm i html-webpack-plugin -D

安装清除和合并依赖(在ts_demo目录下安装)

1
cnpm i clean-webpack-plugin -D
1
cnpm i webpack-merge -D

在src下新建tpl文件夹,在tpl里新建index.html


配置ts_demo下的package.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
{
"name": "ts_demo",
"version": "1.0.0",
"description": "",
"main": "./src/index.ts",
"scripts": {
"start": "webpack-dev-server --mode=development --config ./build/webpack.config.js",
"build": "webpack --mode=production --config ./build/webpack.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"ts-loader": "^9.4.1",
"typescript": "^4.9.3",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1",
"webpack-merge": "^5.8.0"
}
}

最终

使用:npm run start来启动

使用:npm run build来打包

目录结构如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ts_demo
├─ build
│ ├─ webpack.base.config.js
│ ├─ webpack.config.js
│ ├─ webpack.dev.config.js
│ └─ webpack.pro.config.js
├─ dist
│ ├─ app.js
│ └─ index.html
├─ package.json
├─ src
│ ├─ index.ts
│ ├─ package.json
│ └─ tpl
│ └─ index.html
├─ test.txt
└─ tsconfig.json