webpack打包基本配置
webpack打包基本配置
安装webpack及相关基本包
yarn add -D webpack webpack-cli typescript
// 自动生成html文件
yarn add -D html-webpack-plugin
// 内置服务器,热更新
yarn add -D webpack-dev-server
// 每一次编译前清空dist
yarn add -D clean-webpack-plugin
webpack.config.js
// 引入一个包
const path = require("path");
// 引入html插件,自动生成html文件
const HTMLWebpackPlugin = require("html-webpack-plugin");
// 引入clean插件
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
// webpack中的所有的配置信息都应该写在module.exports中
module.exports = {
// development为开发者环境,production为生产环境变量 ,还有一个为none
mode: "development",
// 指定入口文件
entry: "./src/index.ts",
// 指定打包文件所在目录
output: {
// 指定打包文件的目录
path: path.resolve(__dirname, "dist"),
// 打包后文件的名字
filename: "bundle.js",
},
// 指定webpack打包时要使用的模块
module: {
// 指定加载的规则
rules: [
{
// test 指定规则生效的文件
test: /\.ts$/,
// 要使用的loader
use: "ts-loader",
// 要排除的文件
exclude: /node-modules/,
},
],
},
// 配置webpack插件
plugins: [
// new CleanWebpackPlugin(),
new HTMLWebpackPlugin({
// 自定义title
// title: "TS-Webpack",
// 网页模板
template: "./src/index.html",
}),
],
// 用来设置引用模块
resolve: {
extensions: ['.ts', '.js'],
},
};
packages.json
{
"name": "ts-webpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack", // 编译
"start": "webpack serve" // 启动本地服务
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"ts-loader": "^9.2.6",
"typescript": "^4.4.4",
"webpack": "^5.61.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0"
}
}