js-typescript+webpack4工程搭建
js-typescript+webpack4工程搭建
前篇
- 从零搭建TypeScript+webpack4开发环境 - https://juejin.im/post/5e3d65c0518825493c7b4880
流程
安装 nodejs.
1
2$ node -v
v12.14.1初始化项目
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18$ mkdir typescript-lab
$ cd typescript-lab
$ npm init # 一路回车即可, 后面可以自行修改
...
{
"name": "typescript-lab",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes) yes会生成一个 package.json 配置文件
安装 typescript, webpack
1
$ npm install webpack webpack-cli webpack-dev-server typescript ts-loader --save-dev
然后用 cd 到根目录用 tsc 命令初始化
1
2$ tsc --init
message TS6071: Successfully created a tsconfig.json file.会生成一个 tsconfig.json 文件
创建 webpack 配置文件. 在根目录下创建 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
32
33
34
35
36
37
38
39const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
entry: "./src/index.ts", // ts 入口文件
output: {
filename: "main.js"
},
resolve: {
extensions: ['.ts', 'tsx', '.js']
},
module: {
rules: [ // 监听文件的规则
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
//这个参数就可以在webpack中获取到了
devtool: process.env.NODE_ENV === 'production' ? false : 'inline-source-map',
devServer: {
//这个本地开发环境运行时是基于哪个文件夹作为根目录
contentBase: './dist',
stats: 'errors-only', // 只在编译出错是输出日志. string: 'none' | 'errors-only' | 'minimal' | 'normal' | 'verbose'
compress: false, //不启动压缩
host: 'localhost',
port: 8081
},
plugins: [
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: ['./dist']
}),
new HtmlWebpackPlugin({
template: './src/template/index.html' // html 入口文件
})
]
}创建 webpack.config.js 里面需要用到的文件.
创建 ts 入口文件 src/index.ts
1
2let num: number = 888
document.title = 'yangx'创建 html 入口文件. 空文件即可.
安装 ts-loader. 解析ts文件转换成浏览器可以识别的文件
1
$ npm install ts-loader -D
安装 cross-env. 用于设置环境变量的,方便设置开发环境和生产环境
1
$ npm install cross-env -D
安装一些插件
clean-webpack-plugin 能清理一些指定的文件夹
html-webpack-plugin 指定一个编译的模型
1
$ npm install clean-webpack-plugin html-webpack-plugin -D
项目中安装 typescript 依赖
1
$ npm install typescript
在 package.json 文件写指定命令
1
2
3
4"scripts": {
"start": "cross-env NODE_ENV=development webpack-dev-server --config ./webpack.config.js",
"build": "cross-env NODE_ENV=production webpack --config ./webpack.config.js"
},启动运行.
1
2
3
4
5
6
7
8
9$ npm start
> typescript-lab@1.0.0 start E:\ws_js\typescript-lab
> cross-env NODE_ENV=development webpack-dev-server --config ./webpack.config.js
i 「wds」: Project is running at http://localhost:8081/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from ./dist
i 「wdm」: Compiled successfully.done.
踩坑
webpack-dev-server 不是内部或外部命令,也不是可运行的程序
安装下即可
1 | $ npm install webpack-dev-server --save |
参考: https://blog.csdn.net/hzxOnlineOk/article/details/78284101