Created By JishuBao on 2019-03-06 12:38:22

Recently revised in 2019-03-08 12:38:22

 

Welcome to the gold digging world of technology treasure, your star is the biggest motivation for me to write articles! Making the address

Use WebPack4 to create a vue/ React environment. Use webpack4 to create a Vue/React environment. Feel good friends, like the star to go a wave; Feel the article is wrong friends, comment area, QQ group to go a wave; I would be grateful for your advice

Overview of Webpack

Webpack is a modular management tool, which can compress, preprocess, pack on demand, load on demand and so on.

2. Basic concept of Webpack

Before we dive into WebPack, let’s take a look at a few related concepts (in case you’re too lazy to read them) :

  • Entry: Entry, the first step in the build that Webpack performs will start with Entry, which can be abstracted into input.
  • Module: Module, in Webpack everything is a Module, a Module corresponds to a file. Webpack recursively finds all dependent modules starting from the configured Entry.
  • Chunk: a Chunk is a code block. A Chunk is composed of multiple modules for code merging and cutting.
  • Loader: module converter, used to convert the original content of a module into new content as required.
  • Plugin: The extension plug-in broadcasts the corresponding time at specific times in the Webpack construction process. The plug-in can listen for these events and do corresponding things at specific times.

Three, Webpack practical operation (small white entry-level level)

There must be some friends to other articles, baidu certainly met only admire but talk but not practical blogger, or some bloggers just a rough one, cause you what also have no harvest, more see more confused, this article is not the same with those irresponsible blogger (a joke), this paper knife, actual operation, With a small partner from scratch to manually build a Webpack development environment, fine to new folder level (manual funny), for each line of code we see, understand thoroughly!!

Make a new folder

First, create a new folder. Techy likes to create a new folder in the MyProject directory of E disk, named WebpackofVueStage, as shown in the picture below:


Open the folder with an editor

Use the editor to open the folder, I use VSCODE here, which is a Microsoft editor, very easy to use, I suggest friends can try it, as shown below:

Open this folder in the vscode terminal, that is, open the command line in this folder, and typenpm init, will generate onepackage.jsonfile

The following

4. Create a file in the directory

Create a build directory under the home directory to store webPack-related configuration files, and a SRC directory to store source files, including resource files, JS files, CSS files, etc. The directory structure is shown in the picture below. The files are all empty. Techino will lead you to implement this “magnificent” project line by line.

Five, sharpen the knife to knock

Code for Webpack-related files: Here the Webpack files are divided into three files

1. Webpack.base.conf.js (basic code writing)

const path=require('path');
// Use require to import the path module of Node. The path module contains some small tools for handling file paths. Since webpack is based on the node environment, you can directly use the node native module path
Copy the code
const SRC_PATH=path.resolve(__dirname,".. /src")
//path.resolve() resolves a path or a path fragment into an absolute path. Path.resolve () resolves a path or a path fragment into an absolute path. File name. So basically we're extracting the absolute path
Copy the code
entry:{
    main:'./src/index.js'
}
// The entry point indicates which module WebPack should use as a starting point for building its internal dependency graph. Once at the entry point, WebPack finds out which modules and libraries are (directly and indirectly) dependent on the entry point
Copy the code

This article uses vUE as an example to install the dependency packages that need to be installed

npm install vue -S
// Save -d = devDepencies; // Save -d = devDepencies
Copy the code
npm install webpack webpack-cli webpack-dev-server webpack-merge --save-dev
Webpack - CLI is a command line tool for Webpack. This allows us to use Webpack much easier by simply configuring the package configuration file and typing webpack-cli --config webpack.config.js on the command line. Before Webpack 4, the command line tools were integrated into the Webpack. Since 4.0, the Webpack itself is no longer integrated with the CLI. Webpack-dev-server is used for development and debugging, which provides support for Web services, hot updates, interface proxies, and so on. Webpack-merge provides a function that merges arrays and merges objects that create new objects. If it encounters functions, it executes them, runs the result through the algorithm, and again wraps the returned value in the function.
Copy the code
resolve:{
        extensions: ['.vue'.'.js'].alias: {The '@':SRC_PATH
        }
},
//Resolve configures Webpack to find the file corresponding to the module. Extensions: If the import statement does not have a file suffix, Webpack will automatically apply the suffix to try to access the file. Alias: The configuration item uses an alias to map the original import path to a new import path.
Copy the code
module: {rules:[
            {
                test:/\.vue$/.// Preprocessing files by loader allows you to package any static resources other than JS
                use:'vue-loader'
            },
            {
                test:/\.js? $/.use:'babel-loader'.// Exclude files in node_modules
                exclude:/node_modules/.include:SRC_PATH
            },
            {
                test:/\.(woff|svg|eot|woff2|tff)$/.use:[
                    {
                        loader:'url-loader'.include: [resolve('src')].options: {limit:10000}}].exclude:/node_modules/,}},Copy the code

As shown above, the loader shown in the figure needs to be installed

 npm install vue-loader babel-loader url-loader --save-dev
// Rules is a module attribute that specifies the module resolution rule, and use is a rule for each rule that specifies what loader to use. Vue-loader: parses and transforms the. Vue file, extracts the logical code script, style code style, and HTML template, and then sends them to the corresponding loader for processing. Babel-loader is used to convert ES6 to ES5. Url-loader can package images in HTML and CSS as Base64, but js urls with images cannot be compiled successfully. Used to reduce HTTP requests for performance optimization.
Copy the code

When using vue-Loader, make sure that you have introduced plug-ins for Vue

const VueLoaderPlugin = require('vue-loader/lib/plugin');
plugins:[
        new VueLoaderPlugin(),
        // Its job is to copy and apply the other rules you have defined to the corresponding language blocks in the.vue file. For example, if you have a rule that matches /\.js$/, it will be applied to the 
]
Copy the code

Now that the basic webpack file is built, here is the complete code for webpack.base.conf.js:

const path=require('path'); // Path is a module of Node.js that provides widgets for handling file paths const SRC_PATH=path.resolve(__dirname,".. /src");
const VueLoaderPlugin = require('vue-loader/lib/plugin');

module.exports={
    entry:{
        main:"./src/index.js"// The entry point indicates which module WebPack should use as a starting point for building its internal dependency graph. Once inside the entry start, WebPack finds out which modules and libraries the entry start (directly and indirectly) depends on}, resolve:{extensions:['.vue'.'.js'].alias: {The '@':SRC_PATH
        }
    },
    module:{
        rules:[
            {
                test:/\.vue$/,// Preprocessing files by loader allows you to package any static resources other than js.'vue-loader'
            },
            {
                test:/\.js$/,
                use:'babel-loader'// Exclude :/node_modules/, include:SRC_PATH}, {test:/\.(woff|svg|eot|woff2|tff)$/,
                use:[
                    {
                        loader:'url-loader',
                        options:{
                            limit:10000}}], exclude:/node_modules/,}]}, plugins:[new VueLoaderPlugin(), // It is responsible for copying other rules you have defined and applying them to the corresponding language blocks in the.vue file. For example, if you have a rule that matches /\.js$/, it will be applied to the <script> block in the.vue file. }Copy the code

2. Writing webpack.dev.conf.js (development environment)

const webpack=require('webpack');
//require is a native module. If not, go to node_modules and see if it is defined in package.json's main.
Copy the code
const merge=require('webpack-merge');
//webpack-merge provides a merge join array and merge functions that create new objects.
Copy the code
const baseWebpackConfig=require('./webpack.base.conf.js');
// Introduce the basic Webpack setup.
Copy the code
const HtmlWebpackPlugin=require('html-webpack-plugin');
// This is a WebPack plug-in that simplifies the creation of HTML files and serves your WebPack bundled services. This is useful for packages where Webpack includes hashes in the file name, and these hashes change each compilation. The basic function is to generate HTML.
Copy the code
const derServerPort=10000;
// The port number of the development environment.
Copy the code
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
// Identify certain categories of Webpack errors and clean, aggregate, and prioritize them to provide a better developer experience. (Friendly prompt plugin).
Copy the code
npm install friendly-errors-webpack-plugin html-webpack-plugin --save-dev
// The dependencies needed to install the above code
Copy the code
mode:'development'
// In the development environment, process.env.node_env is set to development. Enable NamedChunksPlugin and NamedModulesPlugin
Copy the code
devtool:'cheap-module-eval-source-map'
// SourceMap without column-map simplifies the loaded Source map to a single mapping per row. .
Copy the code
module: {rules:[
            {
                test:/\.css$/.use:[
                    {loader:"style-loader"},
                    {loader:"css-loader"},
                    {loader:"postcss-loader"}]}, {test:/\.(sc|sa)ss$/.use:[
                    {loader:"style-loader"},
                    {loader:"css-loader"},
                    {loader:"sass-loader"},
                    {loader:"postcss-loader"}]}, {test:/\.less$/.use:[
                    {loader:"style-loader"},
                    {loader:"css-loader"},
                    {loader:"less-loader"},
                    {loader:"postcss-loader"}]}, {test:/\.(png|svg|jpg|gif)$/.use:[
                    {
                        loader:'file-loader'.options: {limit:10000,}}]}]},// Simply convert the corresponding suffix to a CSS file
Copy the code
npm install style-loader css-loader sass-loader less-loader postcss-loader file-loader --save-dev
// Use style-loader to add CSS to the DOM by injecting the 
Copy the code
DevServer :{port:derServerPort,// Specifies the port number to listen for requests. Overlay :{// Displays the browser with full-screen overlay warnings when there are errors or warnings in the compiler:false,
            errors:true,
        },
        host:"localhost",
        open:true// The development server will open the browser noInfo:true,// Messages showing webpack information "will be hidden. Errors and warnings are still displayed. https:false,
        hot:true// Enable webpack module hot update compress:true// All services are enabled with gzip compression.true// Output the task progress to the consoletrue,
        useLocalIp:false// This option allows the browser to open proxy:{// proxy server using your local IP"/api":{
                target:"http://localhost:8080",
                changeOrigin:true,
                pathRewrite:{"^api":"/api"}}}}, // The above is the code snippet in WebPack development modeCopy the code
plugins:[
        / / deal with HTML
        new HtmlWebpackPlugin({
            template:'src/public/index.html'.// The development environment requires paths
            inject:'body'.// All javascript resources are placed at the bottom of the body element
            minify:{
                html5:true.collapseWhitespace: true.// Remove unnecessary Spaces from the contents of the generated index.html file to reduce space
            },
            title:'VuE-Router, VUex, Vant and other technologies will be adopted in the project.'.hash:true.favicon:'src/assets/favicon-shield.ico'.// Add the given favicon path to the output HTML
            showErrors:true,})./ / hot update
        new webpack.HotModuleReplacementPlugin(),
        new FriendlyErrorsWebpackPlugin({
            compilationSuccessInfo: {
                messages: [`You application is running here http://localhost:${derServerPort}`].notes: ['Some additionnal notes to be displayed unpon successful compilation']},onErrors: function (severity, errors) {},
            clearConsole: true.additionalFormatters: [].additionalTransformers: []}),new webpack.LoaderOptionsPlugin({
            options: {}})]// Plug-in configuration in the development environment
Copy the code

The complete code of the webpack.dev.conf.js file is as follows:

const webpack=require('webpack');
//require is a native module. If not, go to node_modules and see if it is defined in package.json's main.
const merge=require('webpack-merge');
//webpack-merge provides a merge join array and merge functions that create new objects
const baseWebpackConfig=require('./webpack.base.conf.js');
// Introduce the basic Webpack setup
const HtmlWebpackPlugin=require('html-webpack-plugin');
const derServerPort=10000;
// The basic function is to generate HTML files
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
// A friendly tip

module.exports=merge(baseWebpackConfig,{
    mode:'development'.// In the development environment, process.env.node_env is set to development. Enable NamedChunksPlugin and NamedModulesPlugin
    devtool:'cheap-module-eval-source-map'.// SourceMap without column-map simplifies the loaded Source map to a single mapping per row.
    module: {rules:[
            {
                test:/\.css$/.use:[
                    {loader:"style-loader"},
                    {loader:"css-loader"},
                    {loader:"postcss-loader"}]}, {test:/\.(sc|sa)ss$/.use:[
                    {loader:"style-loader"},
                    {loader:"css-loader"},
                    {loader:"sass-loader"},
                    {loader:"postcss-loader"}]}, {test:/\.less$/.use:[
                    {loader:"style-loader"},
                    {loader:"css-loader"},
                    {loader:"less-loader"},
                    {loader:"postcss-loader"}]}, {test:/\.(png|svg|jpg|gif)$/.use:[
                    {
                        loader:'file-loader'.options: {limit:10000,}}]}]},devServer: {port:derServerPort,// Specify the port number to listen for requests
        overlay:{// Displays full screen overlay of the browser when there is an error or warning in the compiler
            warnings:false.errors:true,},host:"localhost".open:true.// The development server will open a browser
        noInfo:true.// Messages showing webpack information "will be hidden. Errors and warnings are still displayed.
        https:false.hot:true.// Enable module hot update for Webpack
        compress:true.// All services are gzip compressed
        progress:true.// Outputs the task progress to the console
        quiet:true.useLocalIp:false.// This option allows the browser to open using your local IP
        proxy:{// Proxy server
            "/api": {target:"http://localhost:8080".changeOrigin:true.pathRewrite: {"^api":"/api"}}}},plugins: [/ / deal with HTML
        new HtmlWebpackPlugin({
            template:'src/public/index.html'.// The development environment requires paths
            inject:'body'.// All javascript resources are placed at the bottom of the body element
            minify:{
                html5:true.collapseWhitespace: true.// Remove unnecessary Spaces from the contents of the generated index.html file to reduce space
            },
            title:'VuE-Router, VUex, Vant and other technologies will be adopted in the project.'.hash:true.favicon:'src/assets/favicon-shield.ico'.// Add the given favicon path to the output HTML
            showErrors:true,})./ / hot update
        new webpack.HotModuleReplacementPlugin(),
        new FriendlyErrorsWebpackPlugin({
            compilationSuccessInfo: {
                messages: [`You application is running here http://localhost:${derServerPort}`].notes: ['Some additionnal notes to be displayed unpon successful compilation']},onErrors: function (severity, errors) {},
            clearConsole: true.additionalFormatters: [].additionalTransformers: []}),new webpack.LoaderOptionsPlugin({
            options: {// postcss:[
                // require('postcss-plugin-px2rem')({
                // rootValue:75,
                // selectorBlackList:['html'],
                // mediaQuery:true,
                // propBlackList:['75px']
                / /})
                / /,}})});Copy the code

3. Writing code of webpack.prod.conf.js (production environment)

The same code as above is not repeated

const path=require('path');
const DIST_PATH=path.resolve(__dirname,".. /dist");
const CleanWebpackPlugin=require('clean-webpack-plugin');
// Clear files before packing
Copy the code
const BundleAnalyzerPlugin=require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// Analyze the size of the package
Copy the code
const MiniCssExtractPlugin=require('mini-css-extract-plugin');
CSS / / separation
Copy the code
 mode:"production"
 // Process.env.node_env is set to production. Enable FlagDependencyUsagePlugin FlagIncludedChunksPlugin, ModuleConcatenationPlugin NoEmitOnErrorsPlugin, OccurrenceOrderPlugin SideEffectsFlagPlugin and UglifyJsPlugin.
Copy the code
output:{
        filename:"js/[name].[hash].js".path:DIST_PATH
},
Copy the code
module: {rules:[
            {
                test:/\.css$/.use:[
                    MiniCssExtractPlugin.loader,
                    {loader:'css-loader'},
                    {loader:"postcss-loader"}]}, {test:/\.(sc|sa)ss$/.use:[
                    MiniCssExtractPlugin.loader,
                    {loader:'css-loader'},
                    {loader:"sass-loader"},
                    {loader:"postcss-loader"}]}, {test:/\.less$/.use:[
                    MiniCssExtractPlugin.loader,
                    {loader:'css-loader'},
                    {loader:'less-loader'},
                    {loader:"postcss-loader"}]}, {test:/\.(png|svg|jpg|gif)$/.use:[
                    {
                        loader:'file-loader'.options: {limit:10000.name:"[hash].[ext]".outputPath:"images/"}}]}]},// As in development mode, the MiniCssExtraPlugin separates CSS files
Copy the code
plugins:[
        new CleanWebpackPlugin(['dist'] and {root:path.resolve(__dirname,'.. / '),verbose:true}),// Remove dist before each package
        new HtmlWebpackPlugin({
            // Import index.html from the directory into the generated dist
            template:'src/public/index.html'.title:'VuE-Router, VUex, Vant and other technologies are used in the project (product production environment)'.favicon:'src/assets/favicon-shield.ico'.minify: {removeComments:true.collapseWhitespace:true.removeAttributeQuotes:true}}),new BundleAnalyzerPlugin({// Package analysis
            analyzerPort:10000.openAnalyzer:true,}).new MiniCssExtractPlugin({CSS / / separation
            filename:"css/[name].[chunkhash:8].css".chunkFilename:"css/[id].[hash]css"})]Copy the code

So far, the Webpack production environment has been built and the complete code is as follows:

const merge=require('webpack-merge');
const baseWebpackConfig=require('./webpack.base.conf.js');
const webpack=require('webpack');
const path=require('path');
const DIST_PATH=path.resolve(__dirname,".. /dist");
// Clear files before packing
const CleanWebpackPlugin=require('clean-webpack-plugin');
const HtmlWebpackPlugin=require('html-webpack-plugin');
// Analyze package size while packaging
const BundleAnalyzerPlugin=require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
CSS / / separation
const MiniCssExtractPlugin=require('mini-css-extract-plugin');

module.exports=merge(baseWebpackConfig,{
    mode:"production".// Process.env.node_env is set to production. Enable FlagDependencyUsagePlugin FlagIncludedChunksPlugin, ModuleConcatenationPlugin NoEmitOnErrorsPlugin, OccurrenceOrderPlugin SideEffectsFlagPlugin and UglifyJsPlugin.
    devtool:'cheap-module-source-map'.// SourceMap without column-map simplifies the loaded Source map to a single mapping per row.
    output:{
        filename:"js/[name].[hash].js".path:DIST_PATH
    },
    module: {rules:[
            {
                test:/\.css$/.use:[
                    MiniCssExtractPlugin.loader,
                    {loader:'css-loader'},
                    {loader:"postcss-loader"}]}, {test:/\.(sc|sa)ss$/.use:[
                    MiniCssExtractPlugin.loader,
                    {loader:'css-loader'},
                    {loader:"sass-loader"},
                    {loader:"postcss-loader"}]}, {test:/\.less$/.use:[
                    MiniCssExtractPlugin.loader,
                    {loader:'css-loader'},
                    {loader:'less-loader'},
                    {loader:"postcss-loader"}]}, {test:/\.(png|svg|jpg|gif)$/.use:[
                    {
                        loader:'file-loader'.options: {limit:10000.name:"[hash].[ext]".outputPath:"images/"}}]}]},plugins: [new CleanWebpackPlugin(['dist'] and {root:path.resolve(__dirname,'.. / '),verbose:true}),// Remove dist before each package
        new HtmlWebpackPlugin({
            // Import index.html from the directory into the generated dist
            template:'src/public/index.html'.title:'VuE-Router, VUex, Vant and other technologies are used in the project (product production environment)'.favicon:'src/assets/favicon-shield.ico'.minify: {removeComments:true.collapseWhitespace:true.removeAttributeQuotes:true}}),new BundleAnalyzerPlugin({// Package analysis
            analyzerPort:10000.openAnalyzer:true,}).new MiniCssExtractPlugin({CSS / / separation
            filename:"css/[name].[chunkhash:8].css".chunkFilename:"css/[id].[hash]css"]}}));Copy the code

Src-related file code writing

As mentioned above, we have finished coding webPack. Next is the source code related to the preparation in the above code we will find such as index.js, index.html and so on are not code preparation, next we will improve this part of the code. Are you ready?

1. Prepare CSS icon image favicon-shield.ico(ico suffix is graphic image format) and place it in assets folder

2. Add the index. HTML template file to the public folder

<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" The content = "width = device - width, initial - scale = 1.0, user - scalable = no" > < title > < % = htmlWebpackPlugin. Options. The title % > < / title >  </head> <body> <div id="root"></div> </body> </html>Copy the code

3. Compile the entry file index.js and place it in the SRC root directory:

import Vue from 'vue';
// Import Vue mainly completes the method mount on the prototype and initializes the global API.
import App from './App.vue';// Import vue page (write later)
import './styles/reset.css';// Introduce a style reset

Vue.config.productionTip=false;// Block the start of production messages

new Vue({
    el:"#root".// Hang the render result on the HTML with the id root
    render:h= >h(App),// The render function renders a view and then provides it to the EL to mount
});
Copy the code

Parsing the Vue Template tag requires setup dependency

npm install vue-template-compiler --save-dev
Copy the code

4. Write the app.vue page in the SRC directory

<template> <div class="container"><span>{{msg}}</span></div> </template> <script> export default { data(){ return{ </script> <style>. Container {display:flex; justify-content:center; align-items:center; font-size:20px; color:red; box-shadow:5px 5px 5px 5px; } </style>Copy the code

5. Write a style file called reset.css

The purpose of reset is not to make the default style consistent across all browsers, but to reduce the problems that the default style may cause. * The purpose of reset is not to allow default styles to be consistent across all browsers, But to reduce the potential problems of default styles. * create by jsliang */ /** Clearance of inner and outer Margins **/ body, h1, H2, h3, h4, h5, h6, HR, p, blockQuote, /* list elements - formatting elements */ form, fieldset, legend, button, input, Textarea, /* form elements - from elements */ th, td /* table elements */ {margin: 0; padding: 0; } /* Default initialization style */ body{margin:0; padding:0; Font :" Microsoft yahei "; box-sizing: border-box; } body,html{ text-size-adjust: none; /* Text does not change with device size */ width:100%; height:100%; } *{text-decoration: none; list-style:none; } img{border:0px; } /** set the default font **/ body, button, input, select, textarea {font: 18px/1.5 'black ', Helvetica, Sans-Serif; } h1, h2, h3, h4, h5, h6, button, input, select, textarea { font-size: 100%; } /** reset the list element - reset the list element **/ ul, ol {list-style: none; } /** reset the text format element **/ a, a:hover {text-decoration: none; } /** reset the form element **/ button {cursor: pointer; } input { font-size: 18px; outline: none; } /** reset the table element **/ table {border-collapse: collapse; border-spacing: 0; } /** image responsize **/ img {border: 0; display: inline-block; width: 100%; max-width: 100%; height: auto; vertical-align: middle; } /* * By default, box-sizing is content-box, which causes the padding to expand the div. Set border-box for box-sizing when you use div, it solve the problem when you add padding and don't want to make the div width bigger */ div, input { box-sizing: border-box; } /** clear float -clear float **/. Jsbao -clear:after,. Clear :after {content: '\20'; display: block; height: 0; clear: both; } .jsbao-clear, .clear { *zoom: 1; } /** set input placeholder **/ input::-webkit-input-placeholder {color: #919191; font-size: .26rem } /* Webkit browsers */ input::-moz-placeholder { color: #919191; font-size: .26rem } /* Mozilla Firefox */ input::-ms-input-placeholder { color: #919191; font-size: .26rem } /* Internet Explorer */Copy the code

6. Configure the package.json file

npm install cross-env --save-dev
// resolve webpack command set node_env=development unreactive etc can be used cross-platform
Copy the code

Write in the scripts tag in package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."start": "cross-env webpack-dev-server --config build/webpack.dev.conf.js"."build": "cross-env webpack --config build/webpack.prod.conf.js"
 },
Copy the code

7. About Babel

We all know the importance of Babel in programming, of course, building a Vue environment is also indispensable, let’s take a look at the common Babel (new version is out, this article all upgrade to Babel 7.x)

@babel/core: the function of @babel/core is to analyze JS code into AST, which is convenient for each plug-in to analyze syntax for corresponding processing.

npm install @babel/core@7.12. --save-dev
Copy the code

The @babel/plugin-proposal-class-properties function is to convert es6 classes into browser-readable classes

npm install @babel/plugin-proposal-class-properties@7.1.0 --save-dev
Copy the code

@babel/plugin-proposal-decorators make decorators unbrowser-readable

npm install @babel/plugin-proposal-decorators@7.16. --save-dev
Copy the code

@babel/plugin-proposal-function-bind converts the: : binding to a non-browser-readable binding

npm install @babel/plugin-proposal-function-bind@7.0.0 --save-dev
Copy the code

The @babel/plugin-syntax-dynamic-import function is to support the iterative methods associated with promises and arrays

npm install @babel/plugin-syntax-dynamic-import@7.0. 0 --save-dev
Copy the code

The @babel/ plugin-transform-Runtime function will automatically polyfill features not supported by ES5

npm install @babel/plugin-transform-runtime@7.1. 0 --save-dev
Copy the code

Babel/Polyfill: This library will simulate a complete ES2015+ environment. This means you can use new built-in syntaxes like Promise or WeakMap, Static methods such as array. from or Object.assign and instance methods such as array.prototype. includes and generator functions.

npm install @babel/polyfill@7.2. 5 --save-dev
Copy the code

@babel/preset-env is an intelligent preset that allows you to use the latest JavaScript,

npm install @babel/preset-env@7.16. --save-dev
Copy the code

@babel/preset-react: Presets JSX in React

npm install @babel/preset-react@7.0. 0 --save-dev
Copy the code

@ Babel/preset – stage – 0: with the env

npm install @babel/preset-stage0@7.0. 0 --save-dev
Copy the code

With @ @ Babel/runtime: Babel/polyfill

npm install @babel/runtime@7.2. 0 --save-dev
Copy the code

Once you’ve installed Babel, you need to identify it with a file named.babelrc in the SRC directory

{
    "presets":[
        ["@babel/preset-env", {
            "modules": false."targets": {
              "browsers": ["1%" >."last 2 versions"."ie >= 10"]},"useBuiltIns": "usage"}]."@babel/preset-react"]."plugins":[
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
        ["@babel/plugin-proposal-class-properties", {"loose":true}]."@babel/plugin-transform-runtime"."@babel/plugin-proposal-function-bind"."@babel/plugin-syntax-dynamic-import"]}Copy the code

8. Setting external postcss.config.js

Because you reference a plug-in in the Loader without specifying whose plug-in it is, you need to specify an ident, unique identifier. Create the postcss.config.js file in the SRC directory

// Automatically add CSS compatibility properties
module.exports = {
    plugins: [
        require('autoprefixer') ({"browsers": [
                "defaults"."not ie < 11"."last 2 versions"."1%" >."iOS 7"."last 10 versions"]]}});Copy the code
npm install autoprefixer --save-dev
// automatically complete the CSS prefix
Copy the code

Vi. Project operation

Is not as tired as I see it, the first time to write an article many places did not pay special attention to, I hope the next time can be better and better ** pulled so much, do not look at the effect is equal to play rogue!! NPM run start/ NPM start will automatically pop up, you are advised to use Google (manual funny) renderings:

It is very ugly, only one line and vertical center, but our main purpose is not to build webpack!! If you think this article is useful to you, don’t forget to give my Git a thumbs up!!

7. Operation principle of Webpack

The running flow of Webpack is a serial process, from start to finish, the following flow is executed successively:

Process summary:

  • 1. Initialization parameters: Read and merge parameters from configuration files and shell statements to obtain the final parameters
  • 2. Start compiling: initialize the Compiler object using the parameters obtained in the previous step, load all the configured plug-ins, and execute the run method of the object to start compiling;
  • 3. Determine the entry: Locate all entry files according to the entry in the configuration.
  • 4. Module compilation: Starting from the entry file, call all configured Loader to translate the module, find out the module that the module depends on, and then recurse this step until all the entry dependent files have gone through this step;
  • 5. Complete module compilation: After using Loader to translate all modules in Step 4, obtain the final content of each module after translation and the dependencies between them;
  • 6. Output resources: Assemble chunks containing multiple modules one by one according to the dependency between the entry and modules, and then convert each Chunk into a separate file and add it to the output list. This step is the last chance to modify the output content.
  • 7. Output complete: After determining the output content, determine the output path and file name based on the configuration, and write the output content to the file system.

Process details:

The Webpack build process can be divided into the following three phases:

  • Initialization: start build, read and merge configuration parameters, load Plugin, instantiate Compiler.
  • Compilation: issued from Entry, the corresponding Loader is successively called for each Module to translate the file content, and then the Module depends on the Module is found, and the compilation process is carried out recursively.
  • Output: Combine compiled modules into chunks, convert chunks into files, and output them to the file system.

If only one build is performed, the above phases will be executed one at a time in sequence. However, when listening mode is enabled, the flow changes to the following:

If you think my article is good, you can give it a star.Making the address

The next step is to write a simple demo using vue-Router +Vuex+Vant