Title party

Summary of Webpack4 common configuration, including DEMO, step by step in detail, slightly longer, we give the source file at the end of the follow-up.

Preparing the development Environment

- Install Node - Install webpack - NPM init Init projectCopy the code

The directory structure

Write and run a small demo

// src/index.js

import _ from 'lodash'

function create_div_element () {
    const div_element = document.createElement('div')
    div_element.innerHTML = _.join(['kobe'.'cpul'].' ')
    return div_element
}

const div_ele = create_div_element()
document.body.appendChild(div_ele)

Copy the code
// dist/index.html <! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webpack4</title>
</head>
<body>
    <script src="./bound.js"></script>
</body>
</html>

Copy the code
// webpack.config.js

const path = require('path')

module.exports = {
    entry: './src/index.js',
    mode: 'development',
    output: {
        filename: 'bound.js',
        path: path.resolve(__dirname, 'dist')}}Copy the code

Then perform webpack via NPX for packaging.

Or as a script command.

"scripts": {
    "build": "npx webpack -c webpack.config.js"
 }
Copy the code
npx webpack
Copy the code

Open index. HTML in your browser and see that the code executes successfully.

Webpack deal with CSS

Suppose we now need to introduce a CSS file into index.js.

// index.js

import './style/reset.css'
Copy the code

We need to use a special loader to parse the CSS and inject it into the HTML file

 npm i -D css-loader style-loader
Copy the code

Modify the Webpack configuration file

const path = require('path')

module.exports = {
    entry: './src/index.js',
    mode: 'development',
    output: {
        filename: 'bound.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.css/,
                use: ['style-loader'.'css-loader'] // Use order from right to left}]}}Copy the code

At this point you go to NPX Webpack and execute index.html and you will see that the CSS has been injected successfully.

Webpack handles sass files

Now front-end projects are using CSS preprocessors to help make better use of CSS, such as Sass.

Suppose we now need to introduce a base.scss file into index.js. How does WebPack handle sass/ SCSS files?

npm install sass-loader node-sass -D
Copy the code
// src/style/base.scss

$bd-bg: pink;
body {
    background: $bd-bg;
}
Copy the code
// index.js

import './style/base.scss'
Copy the code

More configuration file processing SCSS

const path = require('path')

module.exports = {
    entry: './src/index.js',
    mode: 'development',
    output: {
        filename: 'bound.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.(sc|sa|c)ss$/,
                use: ['style-loader'.'css-loader'.'sass-loader'] // Use order from right to left}]}}Copy the code

Webpack adds a Source map for sass

The source map is configured to help us locate and debug errors, although we don’t need to start it in production.

As in our example above, you’ll notice that after packaging we can’t tell which file the SCSS came from.

Modify the Webpack configuration file.

const path = require('path')

module.exports = {
    entry: './src/index.js',
    mode: 'development',
    output: {
        filename: 'bound.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.(sc|sa|c)ss$/,
                use: [
                    {
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader',
                        options: {
                            sourceMap: true
                        }
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true}}}}Copy the code

Open index. HTML in your browser.

Webpack adds the CSS3 prefix to the CSS

PostCSS is a powerful tool for translating CSS code using JavaScript tools and plug-ins. One of the most common tools we use is PostCSS for Autoprefixer to automatically capture browser popularity and supported properties. And automatically add prefixes to your CSS rules based on this data.

npm i -D postcss-loader autoprefixer postcss-import // postcss-import: Let WebPack listen and compile // postCSs-nextcSS: support CSS4 when using @import CSS filesCopy the code

Modifying a Configuration File

rules: [
    {
        test: /\.(sc|sa|c)ss$/,
        use: [
            {
                loader: 'style-loader'
            },
            {
                loader: 'css-loader',
                options: {
                    sourceMap: true
                }
            },
            {
                loader: 'postcss-loader',
                options: {
                    ident: 'postcss'.sourceMap: true, plugins: loader => [// you can configure multiple plug-ins require('autoprefixer')({
                            browsers: ['> 0.15%in CN']
                        })
                    ]
                }
            },
            {
                loader: 'sass-loader',
                options: {
                    sourceMap: true}}]}]Copy the code

Pull the stylesheet into a separate CSS file and type the version number

The premise of pulling out CSS is that we only do this in production, so your configuration file is mode: production.

Also pull out the CSS and you can’t use style-loader to inject it into HTML files.

npm i -D mini-css-extract-plugin
Copy the code

Configure a script name

"scripts": {
    "dist": "cross-env NODE_ENV=production npx webpack --progress --config webpack.prod.config.js"
  },
Copy the code

Add a webpack.prod.config.js. Of course for the formal project we will split the configuration file and then merge it.

- webpack.base.config.js
- webpack.dev.config.js
- webpack.prod.config.js
- webpack.vue.config.js
Copy the code

The demo didn’t do that here, so it’s a little redundant.

// webpack.prod.config.js

const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin') const devMode = process.env.NODE_ENV ! = ='production'

module.exports = {
    entry: './src/index.js',
    mode: 'production',
    output: {
        filename: 'bound.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.(sc|sa|c)ss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader'
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            ident: 'postcss',
                            plugins: (loader) => [
                                require('autoprefixer')({
                                    browsers: [
                                        'last 10 Chrome versions'.'last 5 Firefox versions'.'Safari >= 6'.'ie > 8'
                                    ]
                                })
                            ]
                        }
                    },
                    {
                        loader: 'sass-loader'
                    }
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: devMode ? '[name].css' : '[name].[hash:5].css'ChunkFilename: devMode?'[id].css': '[id].[hash:5].css'}})]Copy the code

After you pack, you’ll find

At this point, we can only refer to it in index.html, which is obviously inconvenient because our CSS file must be very large. We will solve this problem later, but we will skip it here.

Webpack compresses JS and CSS

Compression is naturally designed to reduce the size of packages and improve loading efficiency, so compression is always configured in production environments.

Compress CSS

Later versions of Webpack should have built-in CSS compression, which is manually configured for now.

npm i -D optimize-css-assets-webpack-plugin
Copy the code

Change the configuration file:

const OptimizeCSSAssertsPlugin = require('optimize-css-assets-webpack-plugin') optimization: {minimizer: [// compress CSS new OptimizeCSSAssertsPlugin({})]}Copy the code

JS compressed

npm i -D uglifyjs-webpack-plugin
Copy the code

Modifying a Configuration File

const UglifyJsPlugin = require('uglifyjs-webpack-plugin') optimization: {minimizer: [// compress JS new UglifyJsPlugin({// there are many ways to configure cache:true,
            parallel: true.sourceMap: trueUglifyOptions: {// do not print warnings if UglifyJs removes unused code:false, output: {// delete all comments comments:false// The most compact output beautify:false}, compress: {// delete all 'console' statements // Also compatible with Drop_console:true// Collapse the variable collapse_vars that is defined but used only once:true// Extract the static value reduce_vars that appears multiple times but is not defined as a variable to reference:true,}}})]}Copy the code

ERROR in js/background.js from UglifyJs Unexpected token: keyword (const).

Uglifyjs-webpack-plugin does not support es6 syntax, please use terser plugin, so we change to use terser plugin, in fact, you can continue to use Uglifyjs-webpack-plugin, just need to work with Babel to go to the next step.

npm install terser-webpack-plugin -D
Copy the code

See terser-webpack-plugin for more information.

Optimization: {minimizer: [// compress JS new TerserPlugin({cache:true,
            parallel: true.sourceMap: true}),]}Copy the code

Subsequent chapters

  • part-2
  • patt-3