说明
这是最近在学习和实践webpack的一次学习笔记,有不足欢迎指正
这里不涉及前端框架部分,单纯是使用webpack
工程目录结构
webpack-demo (学习工程目录)
|---config
|------webpack.base.js (用于公用配置)
|------webpack.dev.js (用于开发配置)
|------webpack.pro.js (用于发布配置)
|---dist
|---src
|------public (静态资源文件)
|----------imgs
|----------js
|----------fonts
|----------less
|----------html
|------index.html (首页)
|------main.js (入口文件)
我们来看看配置吧
package.json
{
"scripts": {
"build": "webpack --config config/webpack.pro.js",
"dev": "webpack-dev-server --config config/webpack.dev.js"
},
"devDependencies": {
"@babel/core": "^7.9.0",
"@babel/preset-env": "^7.9.5",
"babel-loader": "^8.1.0",
"css-loader": "^3.5.2",
"file-loader": "^6.0.0",
"html-webpack-plugin": "^4.2.0",
"less": "^3.11.1",
"less-loader": "^5.0.0",
"mini-css-extract-plugin": "^0.9.0",
"style-loader": "^1.1.3",
"url-loader": "^4.1.0",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3",
"webpack-merge": "^4.2.2"
}
}
针对单入口
//file=>config=>webpack.base.js
//用于公用环境配置
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: "./src/main.js",
output: {
path: path.resolve(__dirname, "../dist"),
filename: "js/bundle.js",
// publicPath: "./",
},
module: {
rules: [
{
test: /\.(css|less)$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
/* options: {
publicPath: "../",
}, */
},
"css-loader",
"less-loader",
],
},
{
test: /\.(png|jpg|gif|jfif)$/i,
use: [
{
loader: "url-loader",
options: {
limit: 8 * 1024,
name: "[name].[ext]",
publicPath: "../imgs",
outputPath: "imgs/",
},
},
],
},
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
},
],
},
plugins: [
new HtmlWebpackPlugin({ template: "./src/index.html" }),
new MiniCssExtractPlugin({ filename: "css/index.css" }),
],
};
//file=>config=>webpack.dev.js
//用于开发环境配置
const base = require("./webpack.base.js"); //非src 旨在node模块
const merge = require("webpack-merge");
const path = require("path");
module.exports = merge(base, {
mode: "development",
devServer: {
contentBase: path.join(__dirname, "../dist"),
compress: true,
port: 3000,
open: true,
hot: true,
},
});
//file=>config=>webpack.pro.js
//用于生产环境配置
const base = require("./webpack.base.js");
const merge = require("webpack-merge");
module.exports = merge(base, {
mode: "production",
});
针对多入口
只需要改变webpack.base.js下的入口为对象格式即可
entry: {
main: "./src/main.js",
index: "./src/js/index.js",
},
关于多个js模块引入共有模块 可以用webpack自带的spilt代码分割即可,参见:这里推荐如果本身共有模块小于30k 可以用,但是本身模块太大就没必要多一次请求了
optimization: {
splitChunks: {
chunks: "all",
},
},
这里只要添加到webpack.base.js里即可,plugins下面