How to use webpack (detailed process)

What is webback?

If you want to manually configure webback step by step, you can follow the following documents.

webpack is a resource loading / packaging tool

project1/
    src/
    dist/

To put it bluntly, it is to package the files in the src directory of the development environment into the dist directory of the production environment.

Packing refers to merging the fragmented files under src and generating them under dist.

Deployment refers to using the dist directory as the root directory of a website for others to access.

How to use webback?

Global installation

npm i -g webpack webpack-cli

View version number

webpack -v      # 4.29.6
webpack-cli -v  # 3.3.0

Create project directory

mkdir project1 && cd project1

Initialize project

npm init

npm init -y (- y parameter is used to install the default when creating package.json)

Partial installation

npm i -D webpack webpack-cli

Create directory structure, files, and content:

project1/
	package.json
	src/
		index.js

Code in src/index.js:

  • When installing an installation package to be packaged into the production environment, npm i -S should be used. The full write method is npm install --save lodash
  • If you install an installation package for the development environment, you should use npm i -D, and the full write method is NPM install -- save dev lodash
// lodash is a js tool library, which is used to operate object, array, number... More convenient
import _ from 'lodash';	// npm install --save lodash
function component(){
    var element = document.createElement('div')
    element.innerHTML = _.join(['Hello', 'webpack'], ' ')
    return element; 
}
document.body.appendChild( component() )

Create directory structure, files, and content:

project1/
	package.json
	dist/
		index.html

Code in dist/index.html:

  • The main.js file does not exist at present
  • You need to package the src/index.js file and its dependent file lodash through webpack
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
</body>
</html>        
<script src="main.js"></script>

On the command line:

npx webpack

Executing npx webpack will take our script as the starting point of the entry, and then output it as main.js

Node 8.2 + provides the npx command to run the webback binaries of the initially installed webback package

Then you can browse dist/index.html

configuration file

Create the webpack.config.js file in the root directory of the project

project1/
	webpack.config.js

Write code and configure package content.

// Using require to introduce the path module (CommomJS specification) in webpack
const path = require('path')
module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'index.js',
        path: path.resolve(__dirname, 'dist')
    }
}

Entry describes the entry; output describes the exit.

Command line execution:

npx webpack --config webpack.config.js

Note: package according to the configuration page. The entry is src/index.js. Merge it into dist/index.js according to the related dependency of the entry page.

It can also be executed directly:

webpack

The two commands are equivalent

NPM script

Considering that it is not very convenient to run the local webback with CLI, we can set the shortcut.

In the scripts object of the package.json file, add the build script. When executing the build script, the actual execution is the webpack command.

"scripts":{
    "abc" : "npx webpack --config webpack.config.js",
    "build": "webpack"
}

Use the npm run build command instead of the previous webpack command.

npm run build   # npm run abc

resource management

Load other resources used by the current project

  • Loading CSS
  • Loading pictures
  • Load font

Loading CSS

Download the module to parse css in js. We need to package js and css together.

npm install -D style-loader css-loader

webpack.config.js configuration rules

module.exports = {
    entry: // ......
    output: // .....
    module: {
        rules:[
            { test:/\.css$/, use:['style-loader', 'css-loader'] }
        ]
    }
}

module.rules represents the packaging rules defined when a module is packaged with webpack.

When packaging a web pack, if you encounter a file ending in. css, use style loader and css loader.

  • Style loader: generate JS string as style node
  • CSS loader: convert CSS to CommonJS module

src/style.css

.hello { color:red }

src/index.js

import './style.css'
function component(){
    // ........
    element.classList.add('hello')
}

On the command line:

npm run build

If you want to use the scss file, you need to install

npm config set sass-binary-site http://npm.taobao.org/mirrors/node-sass

npm install sass-loader node-sass --save-dev

Then configure in the rule:

{ test:/\.scss$/, use:['style-loader', 'css-loader', 'sass-loader'] }

Loading pictures

How to deal with images in CSS and JS?

Installation required:

npm install --save-dev file-loader

Then configure the rules in the web pack.config.js page:

{ test:/\.(png|svg|jpg|gif)$/, use:['file-loader'] }

Create documents and write code

src/
    images/
        1.jpg
        2.jpg
	index.js
		import img from './images/1.jpg'
		myImg = new Image();
		myImg.src = img;
		document.body.appendChild( myImg );
	style.scss
		background: url(../images/2.jpg)

Command line execution:

npm run build

The two pictures will be copied to the dist directory. The web page can be used normally. If you want to configure the path after the pictures are output, you can:

use:[{
    loader:'file-loader', 
    options:{
        name:'[name].[ext]', 
        outputPath:'images'
    }
}]

Load font

Font is a resource that requires file loader or URL loader

npm i -D url-loader 

Rule configuration: (one out of two)

  • File loader saves a separate font file
{ test: /\.(woff|woff2|eot|ttf|otf)$/, use: ['file-loader'] }
  • URL loader will be combined with js
{ test: /\.(woff|woff2|eot|ttf|otf)$/, use: ['url-loader'] }

style.css or style.scss

@font-face{
    font-family: abc;
    src: url(../fonts/Classic brush font.ttf) format("truetype");
}
div{ font-family:"abc" }

command line

npm run build

PC end multi entry

There may be many entries in the PC project, such as index.html, main.html, etc., which can be accessed directly in the browser.

The mobile project SPA is a single page application, with a single entry can be, if it is a traditional PC, then it needs to use a lot of entry pages.

dist/index.html

<script src="index.js"></script>

dist/main.html

<script src="main.js"></script>
// src/main.js
import fn from './main2.js';
fn();

// src/main2.js
export default function(){
    console.log(123)
}

Access these two files separately in the browser. The js files that these two files depend on are all independent, that is, multiple entries and multiple exits.

wepack.config.js

entry:{
    index:'./src/index.js',
    main:'./src/main.js'
},
output:{
    filename:'[name].js',
    path:path.resolve(__dirname, 'dist')
}

Entry describes the entry, which means there are two entries. One is called index, and the other is called main.

output describes the export, filename describes the name of the packed file, [name] is the keyword indicating the entry file name, and path indicates the location of the merged file.

Command line:

npm run build

You can package 2 js files according to the entry configuration

Plug-in unit

Installation:

npm install --save-dev html-webpack-plugin

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin')
entry: { ... },
plugins: [ new HtmlWebpackPlugin({title:'Title block content'}) ],
output: { ... }

The function of HtmlWebpackPlugin is to generate the index.html file in the dist directory,

dist/index.html exists in our current project, so after the command is executed, the previous file will be overwritten,

If dist/index.html does not exist in the project, HtmlWebpackPlugin can also create the index file according to the default configuration.

If there are multiple entries on the PC side, the above code will introduce the files formed by multiple entries into the index.html file.

Clean up dist directory

Every time you execute a webpack compilation, it's best to clean up the previous content and then rebuild it.

npm install clean-webpack-plugin --save-dev

webpack.config.js

const { CleanWebpackPlugin } = require('clean-webpack-plugin')
plugins:[
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin...
]

Error debugging

Webback is to bundle many files together, so if there is a piece of code error, how to locate the error?

src/index.js

Use console.error to simulate an error, execute npm run build to rebuild the bundled file and run the browser.

Errors will be reported in the browser console, because we are accessing the code in the production environment, so the errors are reported in the production environment, so it is not easy to locate errors.

webpack.config.js

entry:{ ... },
devtool: 'inline-source-map'

After adding the devtool configuration, you can locate the error, but remember that this is only for debugging, and you need to shut down during production.

Auto compile and auto refresh

Every time you modify the file, you need to manually npm run build, which is too cumbersome, so you can install it

npm install --save-dev webpack-dev-server

webpack.config.js

devtool: ...
devServer: { contentBase: './dist' }

package.json

"scripts":{
    "start" : "webpack-dev-server --open"
}

Command line run

npm start

Then directly modify the file under src, browse the file under dist in the browser to see the effect.

Webpack dev server -- Open does not generate files under dist, but saves files in memory, and finally needs to be packaged with build.

alias

Long file names can be configured with short aliases, which makes it easier to describe dependent files.

output: ...,
resolve:{
    alias: {
      '@': path.resolve('src'),
      '#': path.resolve('src/images'),
      'fa': path.resolve('src/fonts/font-awesome-4.7.0/css'),
    }
},

Use aliases

//import printMe from '@/print.js'
//import img from '#/1.jpg';
import 'fa/font-awesome.min.css'
<font class="fa fa-home"></font>

You can't use $as an alias. After modifying webpack.config.js, you need to restart npm start

agent

A solution to cross domain problems

src/index.js

var button = document.createElement('input')
button.type = 'button';
button.value = 'Direct request, blocked due to homology policy';
button.onclick = function(){
    fetch('http://www.wyyijiaqin.com').then(response=>response.text()).then(result=>{
        console.log(result)
    })
}
document.body.appendChild( button )


var button = document.createElement('input')
button.type = 'button';
button.value = 'Agent request, can get data';
button.onclick = function(){
    fetch('/api').then(response=>response.text()).then(result=>{
        console.log(result)
    })
}
document.body.appendChild( button )

webpack.config.js

devServer: { 
    contentBase: './dist',
    proxy:{
        "/api": {
            target: "http://www.wyyijiaqin.com",
            pathRewrite: { '^/api': '' },
            //secure: false,
            changeOrigin: true,
        }
    } 
},

Start devServer for the agent to work.

When packing, is the code compressed?

The mode property defines whether the code is compressed when it is packaged.

  • development does not compress code
  • production compression code, default
output: ...,
mode: "development"

post-css

cnpm i postcss-loader -D
cnpm i autoprefixer -D  # Handle css browser compatibility

This module is used to deal with css compatibility. It will automatically prefix css with browser, such as - MS -- WebKit -

style/index.css

span{
    background: red;
    color:white;
    display: flex;
    flex: 1;
    transform: translate(-50%, -50%)
}

index.js

import './style/index.css';

webpack.config.js

{
    test: /\.css$/,
    use: ['style-loader', 'css-loader', {
        loader: 'postcss-loader',
        options:{
            plugins: [
                require('autoprefixer')("last 100 versions")
            ]
        }
    }]
}

If the parameter "require('autoprefixer ') (" last 100 versions ") is changed, an error will occur.

Semantics: if you encounter css files, first use style loader and css loader to process them, then use postcss loader to process them, and use require to introduce the autoprefixer module to process css compatibility

The epidemic situation can stop your body and your desire to learn. The anti war class makes learning persistent.

Published 1 original article, praised 0 and visited 5
Private letter follow

Tags: Webpack npm JSON sass

Posted on Mon, 24 Feb 2020 08:12:51 -0500 by ecco