Goal 1: Compile JS with WebPack

First, download WebPack

Then, since it is a local installation, you need to specify where to find the webPack executor

 ./node_modules/.bin/webpack --version
Copy the code

There’s an easy way to do it

npx webpack
Copy the code

NPX will automatically help us find where webPack is locally

When we run it,

You’ll find an extra dist file with main.js in it and that’s the result of translating index.js

First experience of translating JS

In index.js, write some ES6 syntax that cannot be used directly in the browser, and then translate it with Webpack to see if it can be used

// index.js
import x from './x.js'
console.log(x)

// x.js
export  default 'xxxxx'
Copy the code

Main.js after translation:

In other words, Webpack was acutely aware that our goal was to print the string ‘XXXXX’

Plus webPack configuration file

webpack.config.js

const path = require('path');
module.exports = {
    mode: "development".entry: './src/index.js'.output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].[contenthash].js'}}Copy the code

Goal 2: Understand the use of hashes in filenames

Tip: Cache-control in the HTTP response header

The role of the HTTP cache

Content hashing is that after each modification, a new hash is generated, so the file name changes

So: If the content is not updated, it is cached, and if it is updated, it resends the request with a new file name

Adding a hash is equivalent to adding a version number to the file

So the use of hash in filenames is to increase the cache

Also, since each re-execution of Webpack generates a JS file, in order not to use too much memory, we should delete the existing dist folder before executing each execution

So you need to configure package.json

"scripts": {
    "build": "rm -rf dist && webpack".// This is the sentence
    "test": "echo "Error: no test specified" && exit 1"
  },
Copy the code

After each YARN build, “rm -rf dist && webpack” is executed, that is, delete it first and then compile it again

Goal three generates HTML with WebPack

The installation

yarn add --dev html-webpack-plugin
Copy the code

Yarn build automatically generates an index. HTML

At this point the webpack. Config. Js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    mode: "development".entry: './src/index.js'.output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].[contenthash].js'
    },
    plugins: [new HtmlWebpackPlugin({
        title: 'My App'.template: "src/assets/index.html"}})]Copy the code

“SRC /assets/index.html” as template, title as MY APP to generate a web page

src/assets/index.html: <! doctype html> <html lang="ch-ZN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, User - scalable = no, initial - scale = 1.0, the maximum - scale = 1.0, <meta http-equiv=" x-uA-compatible "content="ie=edge"> <meta http-equiv=" x-uA-compatible" content="ie=edge" htmlWebpackPlugin.options.title %></title> </head> <body> <div id="app"></div> </body> </html>Copy the code

Goal 4 introduces CSS with WebPack

Error:

A CSS Loader is required

Download it

yarn build –dev css-loader

yarn build –dev style-loader

Then modify the configuration file

webpack.config.js

 module: {
        rules: [{test: /.css$/i,
                use: ['style-loader'.'css-loader']]}}Copy the code

Then yarn build

Then if you introduce CSS, WebPack will read the CSS tag and put it in the style tag

The red circle is the loaded CSS

Now we have CSS in the style tag

But what if we want to separate the CSS files?

Download the plugin:

yarn add --dev mini-css-extract-plugin
Copy the code

Add configuration:

Webpack.js.org/plugins/min…

Goal 5: Simplify compilation

Every time you modify the CSS, the first step is to start the server in http-server-c-1 in dist folder. If you want to modify it, you have to break the server, change the CSS, and then start yarn build again. It is too troublesome.

So we want to simplify this process by using webpack-dev-server

First installation

yarn add --dev webpack-dev-server

Configuration method:

Webpack.js.org/guides/deve…

Then change the value from YARN build to YARN Start each time

This will automatically open the browser after each run

Goal 6: Select different compilations based on the schema

Goal: In development mode, generate CSS as a style tag

In production mode, separate CSS files

In development, we use Yarn start,

In production, we use YARN build, CSS to generate the style tag

Can we have two config files to meet this requirement

package.json

"scripts": {
    // Here specify the path to webpack.config.prod.js, taking --config
    "build": "rm -rf dist && webpack --config webpack.config.prod.js"."start": "webpack-dev-server --open"."test": "echo "Error: no test specified" && exit 1"
  },
Copy the code
webpack.config.js
 module: {
        rules: [{test: /.css$/i.// The following line indicates the generation of the style tag
                use: ['style-loader'.'css-loader']}}Copy the code
webpack.config.prod.js

module: {
        rules: [{test: /.css$/i.// The following line indicates the generation of the CSS file
                use: [MiniCssExtractPlugin.loader, 'css-loader']},Copy the code

But the question is, there are only a few lines that are different between the two files, and everything else is exactly the same. Is there a better way?

There are! Use the inheritance idea of JS

First we prepare a webpack.config.base.js and put all the public properties in it

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/index.js'.devtool: 'inline-source-map'.devServer: {
        contentBase: './dist',},output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].[contenthash].js'
    },
    plugins: [new HtmlWebpackPlugin({
        title: 'My App'.template: "src/assets/index.html"})].module: {
        rules: [{test: /.js$/i,
                enforce: 'pre'.use: ['source-map-loader'],},]}}Copy the code

Then webpack.config.js and webpack.config.prod.js inherit this base.js, respectively

First introduce, then use… Base can import all attributes of base

There is one point to note:

If you don’t want to overwrite everything in base, but want to inherit some of it and modify some of it, you can do this inside the property… base.module.rules

module: {
        rules: [
           // Inherit what is needed first. base.module.rules,// Overlay my own configuration so that I don't overwrite all previous configurations with my own configuration
            {
                test: /.js$/i,
                enforce: 'pre'.use: ['source-map-loader'],},]}Copy the code

The final modified configuration files are:

webpack.config.js


/ / into the Base
const base = require('./webpack.config.base')

module.exports = { ... base,// Load all the configurations from base
    mode: "development".module: {
        rules: [{test: /.css$/i,
                use: ['style-loader'.'css-loader'[}]}Copy the code
webpack.config.prod.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
/ / into the Base
const base = require('./webpack.config.base')

module.exports = { ... base,mode: "production".plugins: [
       // Inherit what is needed first. base.plugins,// Overlay my own configuration so that I don't overwrite all previous configurations with my own configuration
        new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css'.chunkFilename: '[id].[contenthash].css'})],module: {
        rules: [
           // Inherit what is needed first. base.module.rules,// Overlay my own configuration so that I don't overwrite all previous configurations with my own configuration
            {
                test: /.css$/i,
                use: [MiniCssExtractPlugin.loader, 'css-loader'[}]}Copy the code

This article is the original article of FJL, the copyright belongs to myself and hungry people valley all, reprint must indicate the source