Recently in the study of some configuration of Webpack, learning the expectation is through webpack can be referenced in HTML files such as CSS, JS, IMG files with version numbers, to avoid the browser cache caused by online requests for resources is still the old version of things.
Start by creating a new Webpack project.
npm init
Copy the code
Install WebPack in the project
npm webpack --save-dev
npm webpack-cli --save-dev
Copy the code
Then you can have fun writing code
I’ll start with the packaging configuration for a single file
In the root directory of your project, create a new webpack.config.js file,
npm install --save-dev html-webpack-plugin mini-css-extract-plugin
clean-webpack-plugin
Copy the code
Let’s take a look at each plugin one by one:
- html-webpack-plugin
When using Webpack, you create an HTML file and automatically insert the webpack static file into the HTML file. You can also use custom templates, such as HTML, PUG, EJS, and hash values. Specific configurable parameters are still many, such as title, meta, etc., please refer to webpack official website
- mini-css-extract-plugin
After WebPack 4.0, CSS styles are extracted from JS files into separate CSS files; This is used in projects where the CSS file is imported into the JS file. When packaging, the plugin recognizes the CSS file and generates a packaged CSS file using the specified path parameters.
- clean-webpack-plugin
Is used to clean up the previously packed files in the next package, please refer to the webpack website
Loader used in the project
- babel-loader
Babel takes JavaScript code written in the latest standards and compiles it down to a version that can be used anywhere today
- html-loader
It defaults to require(“./image.png”) in HTML , and you need to specify the image-file loader in your configuration, such as url-loader or file-loader
- url-loader file-loader
Url-loader has a more configurable limit attribute than file-loader. If the size of the image is larger than this parameter, the file resource can be used. If the value is smaller than this parameter, the image is displayed in base64 format.
- style-loader css-loader
Package the CSS file and insert it into the HTML file.
Single page packaging webpack.config.js configuration
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
const path = require("path");
module.exports = {
mode: "development".entry: path.resolve(__dirname, './src/index.js'),
output: {
filename: "bundle.js".path: path.resolve(__dirname, 'build'),
// libraryTarget: 'umd'
},
module: {
rules: [{
test: /\.html$/.use: [{
loader: "html-loader".options: {
attrs: ['img:src'.'link:href'}}]}, {test: /\.js$/.use: {
loader: "babel-loader"
},
include: path.resolve(__dirname, '/src'),
exclude: /node_modules/}, {test: /\.(jpg|png|gif|bmp|jpeg)$/.use: [{
// loader: 'file-loader',
loader: 'url-loader'.options: {
limit: 8192.// name: '[name].[ext]',
name: '[name]-[hash:8].[ext]'.outputPath: 'images/',}}]}, {test: /\.pug$/.use: {
loader: 'pug-loader'}}, {test: /\.css$/.use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader']},],},plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
hash: true.template: "src/index.html".// template: "src/index.pug",
filename: "bundle.html",}).new MiniCssExtractPlugin({
filename: "bundle.css".chunkFilename: "index.css"})],}Copy the code
Multiple page
In plugin, there are multiple htML-webpack-plugin plugins used to generate corresponding packaged HTML files
Multi-page package webpack.config.js configuration
const getPath = require('./getPath')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
const path = require("path");
module.exports = {
mode: "development".entry: {
main: './src/main/main.js'.side: './src/side/side.js'./ /... getPath.jsPathList,
},
output: {
path: path.resolve(__dirname, 'build'),
filename: 'js/[name].js'.publicPath: '.. / ',},module: {
rules: [{
test: /\.html$/.use: [{
loader: "html-loader".options: {
attrs: ['img:src'.'link:href']}},]}, {test: /\.js$/.use: [{
loader: "babel-loader".options: {
presets: ['es2015']}}],include: path.resolve(__dirname, '/src'),
exclude: /node_modules/}, {test: /\.(jpg|png|gif|bmp|jpeg)$/.use: [{
// loader: 'file-loader',
loader: 'url-loader'.options: {
limit: 8192.name: '[name]-[hash:8].[ext]'.outputPath: './images'.// Specify the file system path to place the target file
publicPath: '.. /images'.// Specify a custom public path to the target file}}}, {test: /\.pug$/.use: {
loader: 'pug-loader'}}, {test: /\.css$/.use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader']},]},plugins: [
new CleanWebpackPlugin(),
// Output HTML file 1
new HtmlWebpackPlugin({
hash: true.template: "./src/main/main.html".// Address of the local HTML file template
filename: "html/main.html".chunks: ['main'],}).new HtmlWebpackPlugin({
hash: true.template: "./src/side/side.html".filename: "html/side.html".chunks: ['side'],})./ /... getPath.htmlPathList,
new MiniCssExtractPlugin({
filename: "css/[name].css".chunkFilename: "./src/[name]/[name].css"]}}),Copy the code
Of course, you can also use a function to get the path of all the files that need to be packed, dynamically inserted into the webpack configuration file
const glob = require("glob");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
/** ** @param {string} globPath file path * @returns entries */
function getPath(globPath) {
let files = glob.sync(globPath);
let entries = {},
entry, dirname, basename, extname;
files.forEach(item= > {
entry = item;
dirname = path.dirname(entry); // Current directory
extname = path.extname(entry); / / the suffix
basename = path.basename(entry, extname); / / file name
// File path
if (extname === '.html') {
entries[basename] = entry;
} else if (extname === '.js') { entries[basename] = entry; }});return entries;
}
const jsPath = getPath('./src/*/*.js');
const htmlPath = getPath('./src/*/*.html');
const jsPathList = {};
const htmlPathList = [];
console.log("jsPath", jsPath)
Object.keys(jsPath).forEach((item) = > {
jsPathList[item] = path.resolve(__dirname, jsPath[item])
})
Object.keys(htmlPath).forEach((item) = > {
htmlPathList.push(new HtmlWebpackPlugin({
hash: true.template: htmlPath[item],
filename: `html/${item}.html`.chunks: [item],
// chunks: [item, 'jquery'],}})))// console.log("htmlPathList", htmlPathList)
module.exports = {
jsPathList,
htmlPathList
}
Copy the code
After packaging, the HTML, CSS, and JPG files in one folder will be packed into the HTML, CSS, and images folders in the build folder, respectively, and the other resource files referenced in the HTML file will also have hash values as version numbers.
Pit:
This project uses “url-loader”: “^ 2.1.0 file -“, “loader” : “^ 4.2.0”
Click to open the project’s Github address