This configuration for diy Webpack 4.x simple configuration, master bypass, beginners learn together! Do not understand the place can be baidu or leave a message

Webpack Chinese official website

Pit: The global Webpack version is 3.x, while the project is 4.x

It is recommended to install a project-specific version of WebPack

npm i -D webpack webpack-cli

Initialization package. Json

NPM init -y or NPM init

Generate the package.json file

{
  "name": "demo_03"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"
}

Copy the code

The first step is to set the compile fields for package.json

There are generally two types of NPM run dev and NPM run build

Webpack adds two convenient points--mode--env.NODE_ENV

  • Mode Two modes
    • — Mode development, compiled JS is not compressed
    • –mode production Specifies the compiled JS compression mode
  • — env.node_dev Sets the environment mode
    • — env.node_env =development Sets the environment to development mode
    • — env.node_env =production Sets the environment to production mode
Webpack --mode development // Set mode to development mode, Webpack --mode production // Set mode to production, Webpack -- env.node_env =development Sets process.env.node_env to the development environment Set process.env.node_env to the production environmentCopy the code

The script package. The json

"scripts": {
    "dev": "webpack --mode development --env.NODE_ENV=development"."build": "webpack --mode production --env.NODE_ENV=PRODUCTION"
  },
Copy the code

How do I get it in webpack.config.js?

const path = require('path');
module.exports = env => {
  // Use env.<YOUR VARIABLE> here:
  console.log('NODE_ENV: ', env.NODE_ENV) // 'production'Console. Log ('Production: ', env.production) // ture

  return {
    entry: './src/index.js',
    output: {
      filename: 'index.js',
      path: path.resolve(__dirname, 'dist')}}}Copy the code

NODE_ENV can also be used to set the development mode and production mode using –mode development

The second step simply starts compiling the Vue project file

Be sure to install vUE related VUE NPM package vue VUe-loader

Note: the console reminds you to install the CSS-Loader and vue-template-Compiler

npm i -D vue vue-loader

Create a new webpack.config.js file in the project file

const configFun = (env)=> {
    return {
        entry: path.join(__dirname, 'src/main.js'), 
        output: {
        	filename: 'index.js', 
        	path: path.resolve(__dirname, 'dist')
    	}
        module: {
            rules:[{
                test: /\.vue$/,
                loader:'vue-loader'
            }]
        }
    },
}
module.exports = (env)=> {
    let config = configFun(env)
    return config;
}
Copy the code

Create a new SRC file in the project file. Create app.js and main.js in the SRC file as follows:

//main.js
import Vue from 'vue'
import App from './app.vue'


let root = document.createElement('div');
document.body.appendChild(root);


new Vue({
	render: (h)=> h(App)
}).$mount(root)
Copy the code
// app.vue
<template>
    <div class="test">{{text}}</div>
</template>
<script>
    export default {
        data() {return {
                text:'hello webpack111! !!!!! '
            }
        }
    }
</script>
<style>
    .text{
        color: # 999;
    }
</style>
Copy the code

The third step is to add the compilation of the other modules

Js ES6, CSS and images

npm i -D babel-core babel-loader babel-preset-es2015 style-loader url-loader file-loader

  • Question 1, If you don’t understand the difference and connection between babel-core babel-loader babel-preset- ES2015, please check out the article of 👇

Differences and connections between babel-loader, babel-core, and babel-preset-env

  • Query 2. Url-loader file-loader relationship

Url-loader converts images that are not set or less than limit to be used by img SRC in base64 format. File -loader is used to parse images larger than limit byte.

Configure the Module in webpack.config.js as follows

module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader'
        },
        {
            test: /\.vue$/,
            loader:'vue-loader'
        },
        {
            test: /\.css$/,
            use: ['style-loader'.'css-loader'] {},test: /\.(gif|jpg|jpeg|svg)/,
            use: [
                {
                    loader: 'url-loader',
                    options: {
                        limit: 1024,
                        name: '[name].[hash:6].[ext]'}},]}]},Copy the code

Create a new. Babelrc file under the project file with the following code

{
  "presets": ["es2015"]}Copy the code

Es2015 depends on the NPM babel-PRESET – ES2015 package you downloaded; “Presets “: [“env”] if babel-preset-env

Step 4 Generate the HTML module

So far there are no HTML files in the project. As the most basic front-end project, Webpack provides us with a package of HTML-webpack-plugin, which can be used to generate HTML files

npm i -D html-webpack-plugin

In the webpack.config.js file as follows

const htmlWebpackPlugin = require('html-webpack-plugin');
plugins: [
    new htmlWebpackPlugin()
]
Copy the code

Html-webpack-plugin configures properties

  • Title Generates the title of the HTML file
  • Filename is the name of the HTML file, which is index.html by default
  • Template Specifies the template to use. HTML EJS EJS
  • Inject Inject has four values: true body head false
    • The default is true. The script tag is located at the bottom of the body of the HTML file
    • The body Script tag is located at the bottom of the body of an HTML file
    • The head Script tag is located in the head of an HTML file
    • False Does not insert the generated JS file, which is almost never used
  • Favicon generates a Favicon for your generated HTML file, and the value is a path
  • Minify Using Minify compresses the generated HTML files. The default is false
  • Cache defaults to true, meaning that a new file is generated when the contents change.
  • ShowErrors When webpack reports an error, it wraps the error message in a Pre. The default value is true.
  • Chunks Chunks are mainly used for multi-entry files [name]
  • ExcludeChunks Excludes some JS
  • XHTML A Boolean value. The default value is false and, if true, the file is referenced in an XHTML-compatible mode.
  • ChunksSortMode script order, default four options: None auto dependency {function}

This article does not do htML-webpack-plugin too much explanation, recommended to view an article

Step 5 webpack – dev – server

Webpack-dev-server is used by developers for configuration during development

The webpack website has a detailed description of the Server under development (devServer)

Add the following code from the webpack.config.js code above

const devConfigFun = (argument)=> {
    argument.devtool = '#cheap-module-eval-source-map';
    argument.devServer = {
        port: '8000',
        host: '0.0.0.0',
        overlay: {
            errors: true
        },
        open: true,
        hot: true
    }
    argument.plugins.push(
    	new webpack.HotModuleReplacementPlugin(),
    	new webpack.NoEmitOnErrorsPlugin()
    )
    return argument;
}

module.exports = (env)=> {
    let config = configFun(env)
    if (env.NODE_ENV === 'development') {
        config = devConfigFun(config)
    }
    return config
};
Copy the code

NODE_ENV is set to be accessible to other files

Add to the original code

Any JS file or vue file can be obtained

// src/main.js
console.log(process.env.NODE_ENV) // development

// src/app.vue
mounted() {
    console.log(process.env.NODE_ENV) // development
}
Copy the code
const configFun = (env)=> {
    return {
        plugins: [
            
            new webpack.DefinePlugin({
                'process.env': {
                    NODE_ENV: env.NODE_ENV === 'development' ? '"development"' : '"production"'// Double colon}}),]}}Copy the code

Modify the script of package.json

  "scripts": {
    "dev": "webpack-dev-server --mode development --env.NODE_ENV=development"."build": "webpack --mode production --env.NODE_ENV=PRODUCTION"
  },
Copy the code

Console NPM run dev automatically opens the default browser with port 8000 by default

Console NPM run build compiled in SRC dist file (including index.htm and index.js)

Webpack 4.x + Vue basic configuration, guaranteed to be able to start and compile, Vue – CLI webpack mode is far from, but in continuous learning and improvement, will continue to update… Stay tuned for

The parcel + vue configuration documentation will also be updated in the future

The code for this project is demo_01 on GitHub