Seems like a long time since last post…
1.
Initializing the project Create the project directory webPack4-demo
1.1 Creating a package.json file and automatically generating NPM init press Enter
1.2 For standard development, code style detection can be introduced, here I use ESlint-standard, install related dependencies, here I use taobao mirror source, NPM access is too slow, please excuse me for not going over the wall.
// esLint plugin dependencies
cnpm i
eslint
eslint-config-standard
eslint-plugin-standard
eslint-plugin-promise
eslint-plugin-import
eslint-plugin-node
eslint-plugin-html -D
Copy the code
Dependent versions are as follows:
Create a.eslintrc file in the root directory of the project to enable ESLint detection. I’m using VScode to install the related ESLint plugin
{
"extends": "standard"."plugins": [
"html"."standard"."promise"]."parser": "babel-eslint"."parserOptions": {
"sourceType": "module"
},
"rules": { // Add a semicolon at the end of the line;
"semi": ["error"."always"]}}Copy the code
For details about how to configure ESlint, see eslint-pluggable JavaScript linter
1.3 Project Development Catalog
2.
Configure the webpack.config.js configuration for the project
2.1 Create webpack.config.js in the root directory of the project and import related modules
const webpack = require('webpack'); / / introduce webpack
const path = require('path'); // Import the path module
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin');
Copy the code
2.2 Obtain multi-page entry files and generate HTML pages
// Get the entry file
const entries = glob.sync('./src/**/index.js');
const entrys = {};
const htmlPlugins = [];
/ / HTML mass production
for (const path of entries) {
const template = path.replace('index.js'.'index.html');
var chunkName = (/.*\/(pages\/.*? \/index)\.js/.exec(path)[1]).replace(/pages\//g.' ');
// Generate an entry file
entrys[chunkName] = path;
// Generate a page template file
htmlPlugins.push(new HtmlWebpackPlugin({
template,
filename: chunkName + '.html'.chunksSortMode: 'none'.chunks: [chunkName, 'js/common'].// favicon: './favicon.ico',
inject: true.hash: false.// Enable hash? [hash]
minify: isDev ? false : {
removeComments: true.// Remove comments from HTML
collapseWhitespace: true.// Folding white space is the same as compressing code
removeAttributeQuotes: true // Remove attribute references}})); }Copy the code
2.3 Global configuration of jquery, jquery code can run according to the online tutorial, but the browser console run error:
new webpack.ProvidePlugin({
$: 'jquery'.jQuery: 'jquery'}}}}}}} An error is as followsCopy the code
In order to solve this problem, I looked up some information and saw that the expose-Loader can be solved perfectly. Without another word, excited immediately CNPM
cnpm install -D expose-loader
// After configuration in webpack.config.js, the above error is resolved
rules: [
{
// require('jquery')
test: require.resolve('jquery'),
use: [{loader: 'expose-loader'.// The names of exposed global variables are as you wish
options: 'jQuery'
},
{
/ / same as above
loader: 'expose-loader'.options: '$'}}]]Copy the code
3.
Copy static files to the dist directory, delete the original dist directory before packaging
3.1 To realize these functions, we need to rely on two plug-ins, copy-webpack-plugin and clean-webpack-plugin
cnpm install -D clean-webpack-plugin clean-webpack-plugin
// Configure the plug-in
new CleanWebpackPlugin(resolve('dist')), // Automatically deletes the specified directory file configuration
new CopyWebpackPlugin([ // Support input an array, static resource import copy
{
from: resolve('src/assets'), // Place the files under SRC /assets
to: './assets' // Copy to assets folder in dist directory}])Copy the code
4.
Handle less, CSS files, automatically add browser prefix
4.1 Installing Dependencies
cnpm install -D
postcss-loader
less less-loader
mini-css-extract-plugin
css-loader
autoprefixer
Copy the code
4.2 Create. Postcss.config. js in the project root directory
module.exports = {
plugins: [
require('autoprefixer') ({browsers: ['cover 99.5% in CN']]}})// Can also be configured in package.json, official recommended mode
"browserslist": ["cover 99.5% in CN"]
Copy the code
4.3 Configure rules and plug-in patterns in webpack.config.js
{
test: /\.css$/.use: [
MiniCssExtractPlugin.loader,
'css-loader'.'postcss-loader']}// Configure in plugins
new MiniCssExtractPlugin({
filename: '[name].min.css'
}),
Copy the code
4.4 NPM run build, package successfully, but the HTML image resource path loading problem. Here I use htMl-withimg-loader plugin to handle CSS background image path problem, add publicPath to image processing rule: ‘.. / ‘
{ // html
test: /\.(htm|html)$/i.loader: 'html-withimg-loader'
}
{ // images
test: /\.(png|jpeg|jpg|gif|svg)(\? . *)? $/.use: [{
loader: 'url-loader'.options: { The options option parameter defines how many images to convert to Base64
limit: 10 * 1024.name: 'assets/images/[name].[ext]'.publicPath: '.. / ' // Resolve the path problem of the CSS background image}}}]Copy the code
4.5 Successfully packaged Dist directory
5.
Import a public HTML file
5.1 Did not use other template syntax to deal with, found an HTML-withimg-loader on NPM, can deal with the problem of image resource path in HTML and import some common HTML files
/ / installation related CNPM instal HTML - withimg - loader - D / / configuration rules {/ / HTML test: / \. (HTM) | HTML $/ I, loader: 'html-withimg-loader'} // Reference template file in HTML file #include(".. /.. /layout/tpl_head.html")Copy the code
6.
The demo address
GitHub – Levai/webPack4_ -: WebPack4 Simple configuration demo