前言
书接上回,上次遗留下来的问题,这次经过修改,似乎是解决了(删除了模板index.html中main.js和css文件的引入)。
新的配置
新增加了一个配置,webpack-merge
,用于合并不同环境下的配置,即开发环境下的配置和公共配置合并处理,测试环境和生产环境也是类似的
// webpack.config.js
// webpack.config.js
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: path.resolve(__dirname, "../src/main.js"), // path.resolve 方法用于生成绝对路径
plugins: [
new webpack.LoaderOptionsPlugin({
// test: /\.xxx$/, // may apply this only for some modules
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "../public/index.html"), // 指定要编译的文件,不指定的话会按照默认的模板创建一个html
title: "webpack练习",
filename: "index.html" // 编译完成输出的文件名
})
]
};
// webpack.config.dev.js
const { merge } = require("webpack-merge");
const config = require("./webpack.config");
const path = require("path");
module.exports = merge(config, {
mode: "development", // 这里就是设置当前配置是什么环境下运行使用的属性
devServer: {
port: 8080, // 端口号
hot: true //文件修改自动刷新
}
});
// webpack.config.prod.js
const { merge } = require("webpack-merge");
const config = require("./webpack.config");
const path = require("path");
module.exports = merge(config, {
mode: "production",
output: {
filename: "[name].[hash].js",
path: path.resolve(__dirname, "../dist_prod"), // 指定打包文件夹
clean: true // 磁盘空间会存有打包后的资源,在再次打包的时候,我们需要先把本地已有的打包后的资源清空,来减少它们对磁盘空间的占用
},
devServer: {
compress: true
}
});
// package.json
{
"name": "webpack-project",
"version": "1.0.0",
"description": "前端项目搭建练习",
"main": "index.js",
"scripts": {
"test": "npm run test",
"build:test": "webpack --config build/webpack.config.test.js",
"dev": "webpack server --config build/webpack.config.dev.js"
},
"author": "leo",
"license": "ISC",
"dependencies": {
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.73.0"
},
"devDependencies": {
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.3",
"webpack-merge": "^5.8.0"
}
}
至此,项目也是成功的跑起来了。