WebpackTS环境搭建

本文最后更新于:2023年7月28日 凌晨

配置TS环境

1
npm init -y

🥝配置

1
2
3
4
5
6
7
8
9
10
11
12
{
...
"main": "./src/index.ts"
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
// 启用配置文件, 需安装依赖`npm install cross-env -D`
"start": "cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack.config.js"
}
...
"license": "MIT"
}

🥝文件目录

1
2
3
4
5
6
7
8
9
10
11
12
└─TS-demo
├─build # 构建配置
├─src # 项目代码
│ ├─api # 公共接口
│ ├─assets # 静态资源
│ │ ├─font # 字体资源
│ │ └─img # 图像资源
│ ├─config # 配置文件
│ ├─tools # 工具函数
│ └─utils # 核心业务代码
└─typings # 模块声明文件

🥝依赖安装

1
npm install typescript tslint -g

🥝初始化TS配置

1
tsc --init

🥝初始化tslint

1
tsl

🥝安装webpack开发依赖

1
npm install webpack webpack-cli webpack-dev-server -D

🥝添加webpack配置

build目录下添加配置文件webpack.config.js

安装TS打包加载器npm install ts-loader -D

安装插件npm install clean-webpack-plugin html-webpack-plugin -D

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
/* 导入插件 */
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')

module.exports = {
/* 打包出入口配置 */
entry: "./src/index.ts", // 项目入口文件
output: {
filename: "main.js" // 出口文件
},

/* 打包文件配置 */
resolve: {
extensions: ['.ts', '.tsx', '.js'] // 自动匹配后缀
},
module: {
rule: [{ // .ts与.tsx打包
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/ // 不打包node_modules下的配置文件
}]
},

/* 开发调试工具,只在开发环境加载 */
devtool: process.env.NODE_ENV === 'production' ? false : 'inline-source-map',

/* 本地服务器配置 */
devServer: {
compress: false, // 是否压缩代码
host: `localhost`,
port: 8080 // 端口
},

/* 插件 */
plugins: [
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: ['./dist']
}),
new HtmlWebpackPlugin({
template: './src/template/index.html'
})
]
}

🥝项目安装TS依赖

1
npm install typescript

WebpackTS环境搭建
https://qingshaner.com/WebpackTS环境搭建/
作者
清山
发布于
2022年2月27日
许可协议