The zero-based development environment to build webpack4.X + Vue

In order to learn and understand what webpack solve pain points of the front, or the need to build their own from scratch a simple development environment,
this tutorial for novice webpack new to learn.

1. Installation node depend on the environment
2. Initialize the project
3. Install webpack
4. Create webpack.config.js
5. Configuration webpack.config.js
6. Complete project development environment configuration

1. Installation node depend on the environment

First webpack node-based environment to run, so pre-install the node itself, online tutorials more, no longer a burden here, you can check whether the installation of installed properly with the following command:

$ node -v
v12.13.1
$ npm -v
6.12.1

2. Initialize the project

Create a new project root directory and CD to the root directory, the following command to initialize the project quickly:

npm init

Configure the default or directly all the way down to Enter:

Press ^C at any time to quit.
package name: (development)
version: (1.0.0)
description: Vue环境搭建
entry point: (webpack.config.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\wamp64\www\web\Vue\development\package.json:

{
  "name": "development",
  "version": "1.0.0",
  "description": "Vue环境搭建",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes)

In this way, it becomes a package.json in the project root swells for managing project information and rely on third-party modules installed.

3. Install webpack

It should be noted that, webpack4 need to install webpack cli, not the same as usual, we installed after a good webpack4 can not be used directly, you will be prompted to install webpack cli.

If you want to use webpack global commands, you can use npm install webpack-cli -g installation.
Tips: It is recommended to install webpack-cli project and using --save-dev or -D configuration will develop into webpack-cli dependence.

npm install webpack webpack-cli -D

4. Create webpack.config.js

For starters, it is recommended to manually create webpack.config.js file, then write yourself a step by step configuration, in order to deepen the impression.
First, in the project root directory, create webpack.config.js, be the first to write general structure:

module.exports = {
    // 开发模式,webpack会根据该模式使用相应的编译配置
    mode: 'development',
    // 打包入口
    entry: '',
    // 打包后资源输出路径
    output: {},
    // 依赖模块,通过设置对应loader去执行一些webpack理解不了的语法资源
    // 如jsx转化为js,less转化为css等,相当于翻译官
    module: {},
    // 依赖插件,处理一些打包压缩、资源优化等任务,比loader功能更强大
    plugins: []
}

According to the project structure, start configuring, as my project structure below:
Here Insert Picture Description

5. Configuration webpack.config.js

5.1 Resource output path configuration item after packaging and packing inlet

const { resolve } = require("path");
module.exports = {
    mode: 'development',
    entry: './src/main.js',
    output: {
        filename: './bundle.js',
        path: resolve(__dirname, './build')
    },
    module: {},
    plugins: []
}

5.2 Some loader configuration rules

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

babel-loader是将ES6等高级语法转换为能让浏览器能够解析的低级语法
@babel/core是babel的核心模块,编译器。提供转换的API
@babel/preset-env 可以根据配置的目标浏览器或者运行环境来自动将ES2015+的代码转换为es5

Modify the configuration webpack.config.js

module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "babel-loader",
                        options: {
                            presets: ["@babel/preset-env"]
                        }
                    }
                ]
            }
        ]
    }

Modify package.json file, add a build attribute properties in scripts for running the compiler command

"scripts": {
    "build": "webpack --config ./webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

main.js ./src/index.js and add the following code files are:

//   ./src/index.js
let test = str => {
    return str.split('').reverse().join('')
}

module.exports = {
    test
}

//   main.js
import { test } from './js/index.js'
console.log(test)
console.log(test('Hello word!'))

Then test package

npm run build

The new index.html static files, packaged files generated bundle.js introduced browser to open index.html, view the output in the console developer, you can see ES6 code is turned into ES5 code:

ƒ test(str) {
  return str.split('').reverse().join('');
}
!drow olleH
  • 5.2.1.1 ES6 / 7/8 Api revolution ES5

Note: babel-loader will convert ES6 / 7/8 and other senior grammar ES5 syntax, but does not convert to the new api. For example, Promise, Iterator, Set, Proxy, Symbol and other global objects, as well as some of the methods defined on the global object (such as Object.assign) will not be transcoded. At this point, we have to use babel-polyfill some do not support the new syntax browser provides compatibility achieved.

installation:

npm install @babel/polyfill -S

Used, it may be packaged directly introduced main.js entry file:

import '@babel/polyfill'

Packaging test, you will find bundle.js file size increases a lot, because that is @ babel / polyfill for compatibility, compatibility with all the code is fully incorporated, which led to a large volume, so we have to be loaded on demand, reducing the compiler package after volume.

  • 5.2.1.2 introduced polyfill demand
    installation of dependencies
npm install core-js -S

The installation is complete you need to modify webpack.config.js configuration:

module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "babel-loader",
                        options: {
                            presets: [
                                "@babel/preset-env",
                                {
                                    //按需加载
                                    useBuiltIns: 'usage',
                                    //指定core-js版本
                                    corejs: {
                                        version: 3
                                    },
                                    //指定到最低浏览器版本的兼容性
                                    targets: {
                                        chrome: '60',
                                        firefox: '60',
                                        ie: '9',
                                        safari: '10',
                                        edge: '17'
                                    }
                                }
                            ]
                        }
                    }
                ]
            }
        ]
    }

After configuring the demand introduction polyfill, babel automatically import the relevant polyfill, this can greatly reduce the volume of the packaged compiled.

npm install less less-loader css-loader style-loader -D
   
css-loader主要的作用是解析css文件, 像@import等动态语法
style-loader主要的作用是解析的css文件渲染到html的style标签内
stylus、less、sass是CSS的常见预处理器,可根据需要安装一种或多种
stylus-loader、less-loader、sass-loader主要是将其对应的语法转换成css语法,可根据需要安装一种或多种

The installation is complete, modify webpack.config.js configuration:

Note: Use loader to order from bottom to top (the right to left)
1, the first to use less-loader .less processing documents into webpack recognized CSS style;
2, and then analyzed by the file css-loader main.js the import syntax analysis of the relationship between the respective css files, merge the files into a respective section css css;
. 3, and finally through the action of style-loader will css-loader css code generated mount the head section of the page.

module: {
        rules: [
            {...},
            {	//处理less资源
		         test: /\.less/,
		         use: ['style-loader', 'css-loader', 'less-loader']
		    }
        ]
    }

index.less file in the project src directory, add the following styles, and import them into packaged entrance main.js file

@color: red;

.box {
    width: 200px;
    height: 200px;
    color: @color
}

Implementation of packaged compilation, refresh the index.html file in a browser, you can see the above styles have been added to the head tag, explain compile successful transformation.

  • For many of the features of CSS3, the need to add a variety of browsers compatible with the prefix, the development process to manually add too much trouble, postcss help you automatically add various browser prefixes
npm install postcss-loader autoprefixer -D

postcss-loader autoprefixer 处理浏览器兼容,自动为CSS3的某些属性添加前缀

Modify the configuration webpack.config.js

module: {
        rules: [
            {...},
            {
                test: /\.less/,
                use: [
                	{
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader'
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: [
                                require('autoprefixer')({
                                    //必须设置支持的浏览器才会自动添加添加浏览器兼容
                                    overrideBrowserslist: [
                                        "last 2 versions",
                                        "> 1%"
                                    ]
                                })
                            ]
                        }
                    },
                    {
                        loader: 'less-loader'
                    }
                ]
            }
        ]
    }
npm install file-loader url-loader -D
    
file-loader可以用来帮助webpack打包处理一系列的图片文件;比如:.png 、 .jpg 、.jepg等格式的图片。
打包的图片会给每张图片都生成一个随机的hash值作为图片的名字
url-loader封装了file-loader,它的工作原理:
1、文件大小小于limit参数,url-loader将会把文件转为Base64;
2、文件大小大于limit,url-loader会调用file-loader进行处理,参数也会直接传给file-loader。

Modify the configuration webpack.config.js

module: {
       rules: [
       		{...},
            {...},
            {
                test: /\.(jpg|jepg|png|gif|svg)$/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        // 当图片大于8k时,交给file-loader处理,否则url-loader会把图片src转成base64编码
                        limit: 1024 * 8,
                        name: '[name].[hash:10].[ext]',
                        outputPath: 'images',
                        // 新版file-loader使用了ES Module模块化方式,将esModule配置为false就可以解决html页面中图片解析地址不正确问题
                        esModule: false
                    }
                }]
            }
        ]
    }
npm install html-withimg-loader -D
    
html中直接使用img标签src加载图片的话,因为没有被依赖,图片将不会被打包。
这个loader解决这个问题,图片会被打包,而且路径也处理妥当。

Modify the configuration webpack.config.js

module: {
       rules: [
       		{...},
            {...},
            {...},
            {
                test: /\.(html|htm)$/,
                use: [{
                    loader: 'html-withimg-loader',
                    options: {
                        outputPath: 'images'
                    }
                }]
            },
        ]
    }
module: {
       rules: [
       		{...},
            {...},
            {...},
            {...},
            {
            	test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
                loader: 'file-loader'
            }
        ]
    }

At present, most of the projects in the core business vue code is .vue end of the file, but the browser does not support parsing of .vue file, it takes webpack will .vue files into the browser can identify the js file.

Install its dependencies

npm install vue-loader vue-template-compiler cache-loader thread-loader -D
npm install vue -S
    
vue-loader 作用解析.vue文件
vue-template-compiler 作用编译模板
cache-loader 作用缓存loader编译的结果
thread-loader 作用使用 worker 池来运行loader,每个 worker 都是一个 node.js 进程
vue 一个用于构建用户界面渐进式的MVVM框架

Modify the configuration webpack.config.js

const { resolve } = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = {
    mode: 'development',
    entry: './src/main.js',
    output: {...},
    module: {
       rules: [
       		{...},
            {...},
            {...},
            {...},
            {...},
            {
                test: /\.vue$/,
                use: [{
                        loader: 'cache-loader' // 缓存loader编译的结果
                    },
                    {
                        loader: 'thread-loader' // 作用使用 worker 池来运行loader,每个 worker 都是一个 node.js 进程
                    },
                    {
                        loader: 'vue-loader', // 解析.vue文件
                        options: {
                            compilerOptions: { // 编译模板
                                preserveWhitespace: false
                            }
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
    	new HtmlWebpackPlugin({
		     template: resolve(__dirname, './src/index.html')
		}),
		new VueLoaderPlugin()
    ]
}

Js html files 5.3 configuration files automatically introduce packages
can be created html files html-webpack-plugin plugin.
Install its dependencies

npm install html-webpack-plugin -D
    
html-webpack-plugin主要有两个作用: 
1、为html文件中引入的外部资源如script、link动态添加每次compile后的hash,防止引用缓存的外部文件问题;
2、以输入模板为基础,生成创建自动引入打包后资源链接的html入口文件。

Modify the configuration webpack.config.js

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: './src/main.js',
    output: {...},
    module: {...},
    plugins: [
    	new HtmlWebpackPlugin({
		     template: resolve(__dirname, './src/index.html')
		})
    ]
}

Delete the last package after repackaging 5.4 configuration file
to install its dependencies

npm install clean-webpack-plugin -D
    
clean-webpack-plugin是删除webpack打包后的文件夹以及文件。

Modify the configuration webpack.config.js

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: './src/main.js',
    output: {...},
    module: {...},
    plugins: [
    	new HtmlWebpackPlugin({
		     template: resolve(__dirname, './src/index.html')
		}),
		new CleanWebpackPlugin()
    ]
}

5.5 Configuration devServer hot update function
every time you want to manually run the complete modification package compiled a lot of trouble, which requires heat update feature enabled, you modify automatically package compiled, we can achieve without refresh page to update our page.
Installation depends

npm install webpack-dev-server -D

Modify the configuration webpack.config.js

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: './src/main.js',
    output: {...},
    module: {...},
    plugins: [...],
    devServer: {
        contentBase: resolve(__dirname, './build'),	// 指定服务器资源的根目录
        compress: true,	// 启用压缩
        open: true,	// 自动打开浏览器
        hot: true,	// 启用热更新功能
        port: 8000	// 自定义端口号
    }
}

Modify package.json file, add a start attribute properties in scripts for opening devServer:

"scripts": {
    "build": "webpack --config ./webpack.config.js",
    "start": "webpack-dev-server",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

Run npm start to open devServer server.

6. Complete project development environment configuration

Handwriting is not easy, I hope to help to you, I feel you can, give a star chant ~

Go to github

UFI
Published 16 original articles · won praise 2 · Views 1188

Guess you like

Origin blog.csdn.net/qq_39075021/article/details/105032389