Webpack pipeline basic work report

Webpack pipeline basic work report

Objective: To scratch the configuration webpack, use pug, typescript, scss.

Reason: webpackAlthough there are many contacts, I haven't configured the project from scratch. Generally, CLIprojects are generated through various tools ( VueCli), which webpackhave been cliconfigured by the tools. In actual development, all relevant problems encountered can be basically solved as long as they are targeted to find information.webpack the understanding of them has always been relatively good. One-sided and trivial, lacking a holistic understanding, let alone "understanding".

I used to jump and walk, but now when I m not busy, go back to the starting point and walk again.

1. Initialize the project

First create a project folder, such aswebpack-demo

Execute in the root directory:

npm init -y
 

Preliminarily set the directory structure and function division of the project

// 
public/
    index.html       	// 
src/                  // 
    assets/           // 
    module/           // 
    main.js            	// 
webpack.config.js   	//webpack 
 

2. Preliminary configurationwebpack

Install the corresponding dependencies

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

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

webpack-cli: In webpack3Zhong, webpackand its CLIin the same package, but in webpack4Zhong has separated the two to better manage them.

html-webpack-plugin: webpack Chinese website , github

Simply put, it is to jsinsert your packaged into yours html.

clean-webpack-plugin: Github , a webpackplugin to delete your build folder before building

Configurationwebpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
    mode: 'production',
    // 
    entry: {
        app: './src/main.js'
    },
    // 
    output: {
        path: path.resolve(__dirname, './dist/'),
        filename: './js/[name].[hash:8].js'
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template: './public/index.html'
        })
    ]
}
 

Configurationpackage.json

{
    "script": {
        "build": "webpack"
    }
}
 

run

npm run build

Successfully packaged :)

3. Configuration pugrelated (by analogy: use vue)

Install the corresponding dependencies

npm install --save-dev pug pug-loader

pug: A kind of htmlrendering template Chinese document

The /public/index.htmlchange pugfile formats

doctype html
htm(lang="en")
head
    meta(charset="UTF-8")
    title= 'webpack-demo'
body
    div#app
 

Configurationwebpack.config.js

module.exports = {
    module: {
        rules: [
            // pug loader
            {
                test: /\.pug$/,
                loader: 'pug-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './public/index.pug' // 
        })
    ]
}

 

4. Configuration ES6support ( babel)

Install the corresponding dependencies

Mainly to use babelofficial documents , Chinese documents-Imprint Chinese

npm install --save-dev babel-loader @babel/core @babel/preset-env

Configurationwebpack.config.js

Increase jsthe processing of files.

module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,
            use: 'babel-loader'
        }
    ]
}
 

Create .babelrcconfiguration file related reference

{
    "presets": ["@babel/preset-env"]
}
 

5. Configuration typescriptsupport

Install the corresponding dependencies

npm install --save-dev typescript ts-loader

Will be main.jschanged tomain.ts

// typescript 
function test(str: string) {
    console.log(`console log ${str}`)
}
test('test')
 

Configurationwebpack.config.js

module.exports = {
    entry: {
        app: './src/main.ts' // 
    },
    module: {
       rules: [
            // typescript loader
           {
               test: /\.ts$/,
               loader: 'ts-loader'
           }
       ]
    }
}
 

Configurationtsconfig.json

Created in the root directory tsconfig.json. Related references

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "sourceMap": true,
        "importHelpers": true
    },
    "exclude": [
        "node_modules"
    ]
}
 

6. Configuration SCSSsupport

Install the corresponding dependencies

npm install --save-dev css-loader mini-css-extract-plugin node-sass sass-loader

  • css-loader: Parses CSSthe file, use importload, and return CSScodes
  • sass-loader: Load and translation SASS/SCSSfiles
  • mini-css-extract-plugin: Lightweight CSSextraction plugin github

Create /src/style.scssfile

$--default-bg-color: #808080;

#app {
    width: 100%;
    height: 100px;
    background-color: $--default-bg-color;
}
 

In /src/main.tsintroducing the style

import './style.scss'
 

Configurationwebpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
    module: {
       	rules: [
          	{
              	test: /\.scss/,
              	use: [
                  	MiniCssExtractPlugin.loader,
                  	'css-loader',
                  	'sass-loader'
              	]
          	}
      	]
    },
    plugins: [
        // CSS 
        new MiniCssExtractPlugin({
            filename: './css/[name].css',
            chunkFilename: '[id].css',
            ignoreOrder: false
        })
    ]
}
 

7. Configuration PostCsssupport

postcssIt is a csstool for compiling, similar Babelto javascriptthe processing of pairs , the commonly used functions are:

  • Use next-generation csssyntax
  • Auto-complete browser prefix
  • css code compression
  • ...

postcssRealize these functions through plug-ins,

Install the corresponding dependencies

npm i --save-dev postcss-loader autoprefixer

  • autoprefixer: postcssPlug-in, use the value in Can I Use to cssadd the browser prefix to it.

Create postcss.config.jsfile

module.exports = {
  plugins: {
    'autoprefixer': {}
  }
}
 

Configurationwebpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test:/\.scss/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          'sass-loader'
        ]
      }
    ]
  }
}
 

8. Configurationbrowserslist

github warehouse address

Regarding browserslist, the official explanation is The config to share target browsers and Node.js versions between different front-end tools.

In the present example, it is in line with autoprefixer, babel, postcssfor use.

Create .browserslistrcfile

last 1 version
> 1%
maintained node versions
not dead
 

9. Configure the processing of image resources

Install the corresponding dependencies

npm install --save-dev file-loader url-loader html-loader

Configurationwebpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|svg|jpg|gif|webp)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 1024 * 30,
              outputPath: 'image',
              fallback: 'file-loader'
            }
          }
        ]
      }
    ]
  }
}
 

have a test

In src/style.scssthe introduction to add a picture, for example,

.app {
	background-image: url("./assets/bg-banner.jpg");
}
 

Create src/index.pugfiles and import pictures, for example

img(src=require('./assets/bg-banner.jpg'))
 

In main.tsthe introduction of theindex.pug

const template: any = require('./index.pug')
document.getElementById('app').innerHTML = template()
 

Then I found that the image path in css was wrong...

Just modify the relevant configuration.

//webpack.config.js
{
  test: /\.scss$/,
   use: [
       // 
     {
       loader: MiniCssExtractPlugin.loader,
       options: {
         publicPath: '../'
       }
     },
     'css-loader',
     'postcss-loader',
     'sass-loader'
   ]
}
 

10. Configure the development environment

webpack-dev-server Can be used for rapid application development.

Install the corresponding dependencies

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

Configurationwebpack.config.js

module.exports = {
    // https://www.webpackjs.com/configuration/dev-server/
    devServer: {
        contentBase: path.join(__dirname, "dist"),
        compress: true, // gzip 
        port: 8090, // 
    }
}
 

Configurationpackage.json

{
    "script": {
        "serve": "webpack-dev-server --open --mode development"
    }
}
 

--open: Open the service directly in the browser.

11. webpackAdvanced work report of assembly line

The script is temporarily unavailable, the date is undetermined, so stay tuned.