Webpack4
使用
注意: 本次使用的 webpack 版本
"devDependencies": {
"ts-loader": "^5.4.5",
"typescript": "^3.4.5",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.3.1"
}
目标
使用 webpack 配合 ts-loader 对 ts 文件编译打包
准备工作
- 安装
webpack
- 安装
webpack-cli
- 安装
webpack-dev-server
- 安装
typescript
- 安装
ts-loader
- 配置
tsconfig.json
- 配置
webpack.config.js
安装工具
webpack
npm install --save-dev webpack
webpack-cli
npm install --save-dev webpack-cli
typescript
npm i --save-dev typescript
ts-loader
npm i --save-dev ts-loader
配置项
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"allowJs": true
},
"include": ["./app/*"],
"exclude": ["./node_modules"]
}
package.json
{
"name": "webpack-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack",
"server": "webpack-dev-server --open"
},
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^5.4.5",
"typescript": "^3.4.5",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.3.1"
},
"dependencies": {}
}
webpack.config.js
module.exports = {
devtool: "eval-source-map",
entry: __dirname + "/app/main.js",
output: {
path: __dirname + "/public",
filename: "bundle.js"
},
devServer: {
contentBase: "./public",
historyApiFallback: true,
inline: true
},
module: {
rules: [{ test: /\.ts$/, use: "ts-loader" }]
}
};
把node_modules忽略掉
.gitignore
node_modules
使用 webpack
构建本地服务器
想不想让你的浏览器监听你的代码的修改,并自动刷新显示修改后的结果,其实 Webpack 提供一个可选的本地开发服务器,这个本地服务器基于 node.js 构建,可以实现你想要的这些功能,不过它是一个单独的组件,在 webpack 中进行配置之前需要单独安装它作为项目依赖
npm install --save-dev webpack-dev-server
配置ts-loader
踩过的坑
提示需要安装webpack-cli
webpack4 中 cli 与 webpack 分开了 需要分别安装,详情请参考:提示需要安装 webpack-cli
网友评论