preface

Using Webpack to build vUE development environment, mainly from the following points

  1. The installation of the webpack
  2. Build a Webpack managed project by following the documentation on the official website to understand some important concepts:
  • The entrance (entry)
  • Output (output)
  • loader
  • Plug-in (plugins)
  • Mode (mode)
  • Browser compatibility, Webpack import(), and require.ensure() require promises. If you want to support older browsers, you also need to load Polyfill before using these expressions.
  • Environment (environment)
  1. Install e Vue, VUe-Router, vuex, and element-UI.
  2. Start performance optimization, improve packaging construction speed, reduce output volume.
  3. This article is included in GitHub, welcome Issues!!

concept

Essentially, WebPack is a static module packaging tool for modern JavaScript applications. When WebPack works with an application, it internally builds a dependency graph that maps to each module required for the project and generates one or more bundles.

Installation/start-up

Install webpack

// Initialize YARN
yarn init -y
// Install webPack locally
yarn add webpack --dev
// Install webpack scaffolding
yarn add webpack webpack-cli --dev
Copy the code

Creating a Configuration File

  • directory
webpack-demo
  |- /src
    |- main.js
    |- App.vue
  |- package.json
+ |- webpack.config.js
  |- index.html
Copy the code
  • webpack.config.js
const path = require("path");
module.exports = {
  entry: {
    app: "./src/main.js",},output: {
    filename: "[name].bundle.js".path: path.resolve(__dirname, "dist"),}};Copy the code
  • index.html
<! DOCTYPE html><html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
Copy the code
  • main.js
import Vue from "vue";
import App from "./App";

const vm = new Vue({
  el: "#app".render: (h) = > h(App),
});
Copy the code
  • App.vue
<template>
  <div id="app">
    <router-view> </router-view>
  </div>
</template>

<script>
export default {
  name: "App"};</script>
Copy the code

Manage resources and Loaders

style-loader css-loader

// yarn
yarn add style-loader css-loader -dev
// webpack.config.js
module: {
    rules: [{test: /\.css$/,
        use: ["style-loader"."css-loader"],},],}// Then you can import the CSS file in main.js
import "./style.css";
Copy the code

less-loader

// yarn
yarn add less less-loader --dev
// webpack.config.js
rules: [{test: /\.less$/,
    use: [
      "css-loader"."less-loader",],}]Copy the code

url-loader file-loader

postcss-loader

Use JavaScript code to handle CSS. It is responsible for parsing CSS code into an Abstract Syntax Tree (AST) and handing it over to plug-ins for processing.

// yarn
yarn ostcss-loader postcss autoprefixer

// webpack.common.js
rules: [{test: /\.css$/i,
    use: [
      "style-loader",
      {
        loader: "css-loader".options: { importLoaders: 1}, {},loader: "postcss-loader".options: {
          postcssOptions: {
            plugins: [[// Add the browser prefix
                "autoprefixer",],],},},},]}]Copy the code

vue-loader

The Vue Loader’s official website

If you are developing a library or multi-project repository (MONorePO), be aware that importing CSS has side effects. Be sure to remove “sideEffects”: false from package.json, otherwise the CSS block will be discarded by WebPack when it is built in production.

// yarn
yarn add vue-loader vue-template-compiler --dev
// webpack.config.js
const { VueLoaderPlugin } = require('vue-loader')
module: {
  rules: [{test: /\.vue$/,
      use: ["vue-loader"],}, {test: /\.css$/,
      use: ["vue-style-loader"."css-loader"],},]; },plugins: [
  new VueLoaderPlugin()
]
Copy the code

babel-loader

// yarn
yarn add babel-loader @babel/core @babel/preset-env --dev
// webpack.config.js
module: {
  rules: [{test: /\.js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: "babel-loader".options: {
          presets: ["@babel/preset-env"],},},},]; }// Create the.babelrc file in the root directory
{
  "presets": [["@babel/preset-env", {
      "modules": false."targets": {
        "browsers": ["1%" >."last 2 versions"."not ie <= 8"}}]]}Copy the code

vue-router

// yarn
yarn add vue vue-router
// Create a router/index file
import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);
// You can refer to related configurations
// https://github.com/PanJiaChen/vue-element-admin/tree/master/src/router
Copy the code

vuex

// yarn
yarn add vuex
// Create a store/index file
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
// You can refer to related configurations
// https://github.com/PanJiaChen/vue-element-admin/tree/master/src/store
Copy the code

element-ui

// yarn
yarn add element-ui
// main.js
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);
Copy the code

Manage output/plugin

To configure the output

// [name] dynamically generates the bundle name according to the name defined at the entry start
output: {
    filename: "[name].bundle.js".path: path.resolve(__dirname, "dist"),}Copy the code

Add HtmlWebpackPlugin to generate an in-memory HTML and append the packed JS file path to the HTML page

// yarn
yarn add html-webpack-plugin --dev

// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');

plugins: [
  new HtmlWebpackPlugin({
      title: 'Manage output'})]Copy the code

Clean the /dist folder clean-webpack-plugin

// yarn
yarn add clean-webpack-plugin --dev

// webpack.config.js
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

plugins: [
  new CleanWebpackPlugin(),
]
Copy the code

MiniCssExtractPlugin separates style files and extracts CSS into separate files that can be loaded on demand

The CSS styles are extracted from the JS file and synthesized into a CSS file

// webpack.prod.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module: {
  rules: [{test: /\.css$/,
      use: [MiniCssExtractPlugin.loader, "css-loader"],},],},plugins: [
  new MiniCssExtractPlugin({
    filename: "css/[name].css".chunkFilename: "css/[name].css"}),].Copy the code

Optimization.splitchunks code separation

// webpack.common.js
optimization: {
  // The plugin can extract the common dependency modules into an existing Entry chunk, or into a newly generated chunk to extract the common resources
  splitChunks: {
    chunks: "all"; }}Copy the code

DefinePlugin injects global variables, typically for environment variables

new Webpack.DefinePlugin({
  "process.env": {
    NODE_ENV: "development".API_URL: "http://xxx/",}})Copy the code

ProvidePlugin defines global variables

new Webpack.ProvidePlugin({
  "Vue": ["vue"."default"]})Copy the code

Parameter Description Value IgnorePlugin Filters package files to reduce the package size

// webpack.prod.js
plugins: [
  new Webpack.IgnorePlugin(/.\/lib/./element-ui/)]Copy the code

Uglifyjs-webpack-plugin compresses JS files

Packaging for production environment

// yarn
yarn add uglifyjs-webpack-plugin --dev

// webpack.prod.js
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
optimization: {
  minimizer: [
    new UglifyJsPlugin({
      test: /\.js(\? . *)? $/i,
      exclude: /node_modules/}})],Copy the code

Copy-webpack-plugin copies files to a directory

// yarn
yarn add copy-webpack-plugin --dev

// webpack.prod.js
const CopyWebpackPlugin=require('copy-webpack-plugin');
plugins: [
  new CopyWebpackPlugin({
    patterns: [{ from: "static".to: "./static/json"}],})]// Form to starts at the root node
Copy the code

Optimize – CSS -assets-webpack-plugin compression CSS styles

// yarn
yarn add optimize-css-assets-webpack-plugin --dev

// webpack.prod.js
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin")
plugins: [
  new OptimizeCssAssetsWebpackPlugin(),
]
Copy the code

Image-minimizer-webpack-plugin optimizes images

// yarn 
yarn add image-minimizer-webpack-plugin --dev

// webpack.prod.js
const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');
plugins: [
  new ImageMinimizerPlugin({
    test: /\.(jpe? g|png|gif|svg)$/i,}),]Copy the code

Friendly-errors -webpack-plugin friendly error prompt

// yarn
yarn add friendly-errors-webpack-plugin --dev

// webpack.dev.js
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
plugins: [
	new FriendlyErrorsWebpackPlugin({
		compilationSuccessInfo: {
      messages: [
        "App running at:"."local: http://localhost:8080"."network: http://192.168.101.7:9998",],},})],Copy the code

Configuring the Development Environment

Use the source map

When Webpack packages source code, it can be difficult to trace the original locations of Errors and warnings in the source code.

// webpack.dev.js
devtool: "inline-source-map".Copy the code

Use the webpack – dev server. –

Hot updates reload in real time

// yarn
yarn add webpack-dev-server --dev
// webpack.dev.js
devServer: {
   contentBase: './dist',},// package.json
"scripts": {
   "start": "webpack server --open"
},
Copy the code

Configure hot module replacement

// webpack.config.js
const webpack = require('webpack');

devServer: {
    contentBase: './dist'.hot: true
},
plugins: [
    new webpack.HotModuleReplacementPlugin()
],
Copy the code

tree shaking

Remove dead-code from JavaScript context

// webpack.dev.js
// In the development environment packaging can output uncompressed code; Production environment packaging compresses the code
optimization: {
  // Tell WebPack to decide which exports to use for each module
  usedExports: true
}

// package.json
{
  "name": "your-project"./** * All files are side-effect-free. The sideEffects value is false to indicate that all files have no side effects. ["*.css"] - If you use a csS-loader like this in your project and import a CSS file, you need to add it to the Side Effect list to avoid accidentally removing it in production mode */
  "sideEffects": false
}
Copy the code

It’s a useful feeling, but your tree-shaking is not useful

Configuring the Production Environment

Install the merge

// yarn
yarn add webpack-merge --dev
Copy the code

Write separate WebPack configurations for each environment

// Adjust the WebPack configuration file
- webpack.config.js
+ webpack.common.js;
+ webpack.dev.js;
+ webpack.prod.js;

// introduced in.dev and.prod files
const { merge } = require("webpack-merge");
module.exports = merge(common, {
  mode: "development/production". Configuration information}Copy the code

Change the package. The json

"scripts": {
  "start": "webpack server --open --config webpack.dev.js"."build": "webpack --config webpack.prod.js"
},
Copy the code

Building performance

portal

The general environment

Update to the latest version

Use the latest WebPack, Node, NPM/YARN versions

loader

Apply the Loader to the minimum number of modules necessary, and by using the include field, apply the Loader only to the modules that actually need to be converted

Smaller = faster

Reduce the overall size of the compiled results to improve build performance. Try to keep chunks small.

  • Use fewer/smaller libraries
  • Use SplitChunksPlugin in multi-page applications
  • Remove unreferenced code

cache

Caches generated Webpack modules and chunks to improve build speed.

The development environment

Devtool

In most cases, the best option is eval-cheap-module-source-map

Minimizing Entry Chunk

optimization: {
  runtimeChunk: true,}Copy the code

The output does not contain path information

output: {
  pathinfo: false,}Copy the code

The production environment

Whether Source Maps are necessary

conclusion

At the beginning of learning Webpack, I felt so dry that I didn’t know where to start looking at so many things on the official website. But now I have a good idea:

  • Start by following the instructions in the guide to configure a simple WebPack from top to bottom, so that you have a general idea of the configuration
  • And then we look at the concept, which serves as a link between the preceding and the following, which has an in-depth explanation of the parameters
  • The next step is to learn configuration with loader and Plugin
  • And finally, if you want to go deeper, look at the API

It’s not enough to use it. You also have to learn how to express what you’ve learned:

  • What does Webpack want to know when the interviewer asks him
  • A dozen more Webpack interview questions
  • If you’re still clueless after reading the official Webpack documentation, you’re an idiot
  • [10,000 words summary] One article thoroughly understand the core principle of Webpack
  • Webpack HMR principle analysis

Vocabulary:

  • What is a chunks module in a Webpack