1.前言
最近在系统重新的学习下webpack,但是最新的是5x,目前常用的还是 4x
,而且准备过段时间搞 Vite
所以也就不准备学5了。在重学webpack4的过程遇到一些问题,仅此做个笔记吧。
2.版本
学习过程发现很多问题都和版本不匹配有很大关系
所以先把版本列出来 ,相信我 能避免很多坑,不信你不按版本试试 😜😜😜😜
"webpack": "^4.46.0", "webpack-cli": "^3.3.12", "webpack-dev-server": "^3.11.2", "mini-css-extract-plugin": "^1.6.0", "css-loader": "^5.2.4", "file-loader": "^6.2.0", "html-loader": "^1.3.2", "html-webpack-plugin": "^3.2.0", "less": "^2.7.3", "less-loader": "^4.1.0", "style-loader": "^2.0.0", "url-loader": "^4.1.1"
3.输出的配置
如果用 node的path模块也遇到些小问题索性换了个写法
output: { filename: "js/built.js", path: __dirname +"/build" },
4.简洁的webpackconfig.js配置
const HtmlWebpackPlugin = require("html-webpack-plugin") module.exports = { entry: "./src/js/index.js", output: { filename: "js/built.js", path: __dirname +"/build" }, module: { rules: [ { test: /\.less$/, use: [ "style-loader", "css-loader", "less-loader" ] }, { test: /\.css$/, use: [ // "style-loader", // 提取js中的css成单独的文件 MiniCssExtractPlugin.loader, "css-loader" ] }, { test: /\.(jpg|png|gif)$/, loader: "url-loader", options: { limit: 8 * 1024, name: "[name]_[hash:10].[ext]", outputPath:"imgs" } }, { test: /\.html$/, loader:"html-loader", }, { exclude: /\.(less|css|js|html|jpg|png|gif)$/, loader: "file-loader", options: { name: "[name]_[hash:10].[ext]", outputPath:"media" } } ] }, plugins: [ new HtmlWebpackPlugin({ template:"./src/index.html" }), new MiniCssExtractPlugin({ // 重命名 filename:"css/built.css" }) ], mode: "development", devServer: { contentBase: __dirname + "/build", compress: true, port: 3000, open: true } }