In actual development requirement, we may not be able to is to use a single page development framework (for example vue, the react), these requirements are mainly based on the perspective of SEO (of course you can use the service side rendering solution, here we do not consider), then we need the front end of the traditional mode of development, the traditional mode will have CSS compatibility and compression, Base64 reduces HTTP requests, common code introduction, JS modularization and other basic issues. The documentation for wePack multipage packaging is abundant, so don’t be alarmed if you encounter problems online or go to the official documentation (WebPack Documentation – Portal). This article is based on the latest version of WebPack to implement multi-page packaging, which not only solves the basic issues mentioned above but also adds practical features such as local services, self-updating modifications, and automatic introduction of common code. The WebPack framework for this article has been opened source to Githua.

Here we use the feature-oriented webPack5 multipage packaging configuration introduction

Function Configuration

1. Initialize WebPack

NPM init NPM install webpack webpack-cli -g // replace -g with --save-dev if the webpack-cli init is installed locally

2. Image file and other file processing, WebPack5 is concentrated in the Asset module, before using file-loader, URl-loader, raw-loader three

Asset /resource splits the resource into separate files and exports the url, just as the previous file-loader does. Asset /inline exports the resource as a dataURL (url(data:)). Asset /source exports resources as source code (source code). The asset is automatically exported as a separate file or as a dataURL (default: 8KB). Asset size limit is set for url-loader.



The module: {rules: [{test: / \. (eot | SVG | the vera.ttf | woff | woff2 | PNG | JPG | GIF) $/ I type: "asset", the generator: {/ / output filename filename: 'static/[hash][ext][query]'}}]} // You can also limit the size of the processing

3, processing HTML files, in order to bind friends in the background is not compressed operation, processing HTML icon and resources


module: { rules: [ { test: /\.html$/, loader: 'html-loader', options: { minimize: Source: {list: ['...', {tag: 'script', attribute: 'SRC ', type: 'src', filter : () => false, }, { tag: 'link', attribute: 'href', type: 'src', filter : () => false, } ] } } } ] }

4, processing JS, CSS compatibility and compression


const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const stylesHandler = MiniCssExtractPlugin.loader; Plugins: [new CssMinimizerPlugin () / / CSS compression], the module: {rules: [{test: / \. (js | JSX) $/ I, loader: "babel-loader", }, { test: /\.css$/i, use: [stylesHandler, "css-loader", "postcss-loader"], } ] }

5, common code processing, this processing is when multiple pages (>=2) have a common introduction to do a package to introduce to multiple pages, thus saving money to reduce HTTP requests. The automatic introduction of public files is covered below.

const MiniCssExtractPlugin = require("mini-css-extract-plugin"); Plugins: [// merge CSS new MiniCssExtractPlugin({filename: 'CSS /[name]/[name].[hash].css'}), new CopyPlugin({patterns: [{from: path.resolve(__dirname, 'static'), to: 'static' } ], }) ] optimization: { splitChunks: { cacheGroups: {/ / packaging Commons public module: {/ / initial extract the public portion of the entry file chunks said: 'initial', / / the number of documents at least minChunks extract the public parts: 2, / / said to extract the public part of the size of the smallest minSize: 0, // name the extracted file name: 'Commons'}}}}

6. Import file and template for engineering configuration

Wepack.batch.entry.js (create)

const path = require('path') const glob = require('glob') const HtmlWebpackPlugin = require("html-webpack-plugin"); Const entryTemplate = [] exports.entry = () => { seekAllFile() setEntryTemplate() return { entry, Const seekAllFile = (parent = 'pages/*') => {const fileList = glob.sync(path.resolve(__dirname, parent)) if (fileList.length > 0) { fileList.forEach(file => { const regJs = file.match(/.*\/(.*js)/i) if (regJs ! == null && regJs[1]) { const jsName = regJs[1] const key = jsName.match(/(.*).js/i)[1] entry[key] = publicPath + parent.replace(/\*/, '') + jsName } else { const parentPath = parent.replace(/\*/, '') const reg = new RegExp(parentPath + '(.*)', 'i') const folder = file.match(reg)[1] if (! file.match(/.*\/(.*?) \.. */)) {console.log(file) seekAllFile(parentPath + folder + '/*')}})} else {return}} // Set the template file for the entry file const setEntryTemplate = () => { Object.keys(entry).forEach(key => { entryTemplate.push(new HtmlWebpackPlugin({ template: entry[key].replace(/\.js/, '.html'), filename: key + '.html', chunks: [key], inject: 'body', minify: false })) }) }

All files under pages will be automatically set to entry and entry file (support unlimited nesting), but the structure is required as follows

Pages /index/index.js index. HTML The js file name is the same as the HTML file name

So the entry file is js and the template is HTML


const batch = require('./wepack.batch.entry')['entry'](); {entry: batch.entry, plugins: [// batch.entryTemplate,]}

7. Automatic import of public files, provided that the automation folder is created in the root directory, the imported resources in the directory index.js will be imported into each template

Webpack. Automation. Load. Js (create)

// Automate the introduction of public files (such as reset.css) /** * @desc: Automatic import of public files - all templates * @param {Object} batch.entry Entry file * @param {Array} Batch. entryTemplate template */ exports.automation = (batch) => { batch.entry['automations'] = './automation/index.js' batch.entryTemplate.forEach(item => { item.userOptions.chunks.unshift('automations') item.userOptions.chunksSortMode = 'manual' }) }


const batch = require('./wepack.batch.entry')['entry'](); Const autoLoad = the require (". / webpack. Automation. The load ') / / automatic introduce automation/index freely configurable autoLoad. The contents of the js - automation (batch)


import '.. /common/css/reset.css'

In this way, each entry file template will introduce reset. CSS, the core function is to configure the chunks of HtmlWebpackPlugin

8, the local service and modify from the update


const { CleanWebpackPlugin } = require('clean-webpack-plugin'); output: { path: path.resolve(__dirname, "dist"), filename: 'js/[name]/[name].[hash].js' }, devServer: { contentBase: path.resolve(__dirname, "dist"), compress: true, hot: false, open: true, port: 8080, }, plugins: [// clean the generated folder in build new CleanWebpackPlugin(),]

The basic configuration of webPack5 multipage packaging is described above. The demo has been open source to Github (Git – portal). If you have questions about the use of the demo, please ask questions or git issues