@TOC

The local environment

Node -v // v9.1.0 NPM -v // 6.5.0 webpack -v // 4.32.2 webpack-cli -v // 3.3.2Copy the code

Note that webpack4+ requires a separate installation of Webpack-CLI

start

1. Initialize the project

npm init 
Copy the code

Generate package.json file all the way to Enter (tip: NPM init -y saves the tedious enter)

2. Install dependencies

npm i webpack webpack-cli webpack-dev-server --save-dev
Copy the code

Go to the WebPack documentation for further information on these dependencies

Depending on the success of the installation, let’s start

3. Configure directory files

Create a folder named index.html webpack.config.js SRC from the right mouse button in the root directory or:

// window
type >webpcak.config.js 
type>index.html md SRC // touch webpcak.config.js touch index.html SRCCopy the code

Create main.js under SRC

Now the directory is as follows

project/
        src/
            main.js
        webpack.config.js
        index.html
        package.json

Copy the code

As follows:

//index.html<! DOCTYPE html><html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Webpack builds from scratch</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

Copy the code
// webpack.config.js
const path = require('path');
const webpack = require('webpack');
modul.exports = {}
Copy the code

4. Configure index.html and webpack.config.js

First modify main.js as follows:

// src/main.js
console.log('hello world');
Copy the code

Webpack.config.js is modified as follows:

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

module.exports = {  Module. exports commonJS specification
  entry: './src/main.js'.// Project entry file, webpack will start from main.js and pack all dependent JS
  output: {
    path: path.resolve(__dirname, './dist'), // The packaged output path of the project can be modified
    publicPath: '/dist/'.// The devServer access path is modifiable
    filename: 'build.js' // The file name can be changed after packaging
  },
  devServer: {
    historyApiFallback: true.// When using the HTML5 History API, the `index.html` page will likely have to be served in place of any `404` responses
    overlay: true //Shows a full-screen overlay in the browser when there are compiler errors or warnings. Disabled by default. If you want to show only compiler errors}};Copy the code

Core in webPack configuration:

  • Entry: webPack packaging entry (not code execution entry);
  • Output: static resource file generated after webpack packaging, which is eventually referenced by HTML;
  • Loader: Converts non-JS files into JS files that webpack can process. Processing of JS files;
  • Plugins: Just as the name suggests — auxiliary plug-ins in the webpack packaging process;

Index.html has been modified as follows with the introduction of packaged JS

// index.html<! DOCTYPE html><html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Webpack builds from scratch</title>
</head>
<body>
<div id="app"></div>
</body>
<script src="/dist/build.js"></script>
</html>

Copy the code

Package. json is modified as follows:

"scripts": {
    "dev": "webpack-dev-server --open --hot",
    "build": "webpack --progress --hide-modules"
  },
Copy the code

Webpack-dev-server starts a static resource Web server — the hot parameter starts hot updates

Restarting the service

npm run dev
Copy the code

Open the console and see hello World output

5. Start of vue

Install the vue

npm install vue --save
Copy the code

Modify main.js as follows

// src/main.js
import Vue from 'vue';
// import Vue from 'vue/dist/vue.esm.js'// You are using the run-time only build of Vuewhere the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build

// console.log('hello world');

var app = new Vue({
  el: '#app',
  data: {
    mess: 'Hello, [email protected]! '}})Copy the code

Now modify index.html as follows:

// index.html<! DOCTYPE html><html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Webpack builds from scratch</title>
</head>
<body>
<div id="app">
	{{ mess }}
</div>
</body>
<script src="/dist/build.js"></script>
</html>

Copy the code

Restarting the service

npm run build
npm run dev
Copy the code

At this time

Information search found: Vue has two forms of code compiler (template) model and the runtime (run) the vue module package. The default to the main field of json runtime pattern, pointed to “dist/vue.runtime.com mon. Js” position. This has been a feature of Vue since it was upgraded to 2.0.

But at this point we’ll write main.js as

// src/main.js
import Vue from 'vue';
// import Vue from 'vue/dist/vue.esm.js'// You are using the run-time only build of Vuewhere the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build

// console.log('hello world');

var app = new Vue({
  el: '#app',
  data: {
    mess: 'Hello, [email protected]! '}})Copy the code
Solution 1
// src/main.js
//import Vue from 'vue';
 import Vue from 'vue/dist/vue.esm.js'// You are using the run-time only build of Vuewhere the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build

// console.log('hello world');

var app = new Vue({
  el: '#app',
  data: {
    mess: 'Hello, [email protected]! '}})Copy the code

Because vue2.0 defaults to Runtime mode, you need to compile.vue files into JavaScript code with vue-loader tools such as Webpack.

Solution 2 (General operations)
// webpack.config.js
const path = require('path');
const webpack = require('webpack'); Module. exports = {//module.exports commonJS specification entry:'./src/main.js'Output: {path: path.resolve(__dirname,) {path: path.resolve(__dirname,)'./dist'), // The package file path of the project publicPath:'/dist/'// Access path filename from devServer:'build.js'// Packaged filename}, devServer: {historyApiFallback: true,
    overlay: true}, resolve: {// change the alias, import Vue from 'Vue' this line of code is resolved to import Vue from 'Vue /dist/vue.esm.jsalias: {
      'vue$': 'vue/dist/vue.esm.js'}}};Copy the code

This change is the same as last time, but much more elegant…

Solution 3

Modify the main.js schema

  1. The compiler model
// src/main.js
/ / the compiler model
new Vue({
  el: '#app',})Copy the code

2. The runtime patterns

New Vue({render: h => h(App) // app.vue});$mount("#app")
Copy the code

Replace 1 with 2, but we recommend plan 2;

The final page is displayed as follows:

Introduce CSS and SCSS

Webpack default support is js modularization, if you need other types of files also support modular development, you need to introduce the corresponding loader to parse!

Installation-dependent dependencies

npm i node-sass css-loader vue-style-loader sass-loader --save-dev
Copy the code

Webpack.config.js is modified as follows

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

module.exports = {  / / module exports commonjs specification
  entry: './src/main.js'.// The project entry file, webpack will start from main.js and load and pack all dependent JS files
  output: {
    path: path.resolve(__dirname, './dist'), // The package file path of the project
    publicPath: '/dist/'.// Access path through devServer
    filename: 'build.js' // The packaged file name
  },
  devServer: {
    historyApiFallback: true.overlay: true
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'}},module: {
     rules: [{test: /\.css$/.use: [
           'vue-style-loader'.'css-loader'],}, {// scss
         test: /\.scss$/.use: [
           'vue-style-loader'.'css-loader'.'sass-loader'],}]}};Copy the code

At this point both SCSS and CSS can be used in development and modularization is introduced

ES6 => ES5

Introduce dependencies using bable translation

npm i babel-core babel-loader babel-preset-env babel-preset-stage- 3 --save-dev
Copy the code

Babel-preset -stage is a crossover rule for syntax proposals of different stages (there are 4 stages), and one is selected, of which 0 is the most powerful

npm install –save-dev babel-preset-stage-0 npm install –save-dev babel-preset-stage-1 npm install –save-dev babel-preset-stage-2 npm install –save-dev babel-preset-stage-3

// .babelrc
{
  "presets": [["env", { "modules": false}]."stage-3"]}Copy the code

Also modify webpack.config.js

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

module.exports = {  / / module exports commonjs specification
  entry: './src/main.js'.// The project entry file, webpack will start from main.js and load and pack all dependent JS files
  output: {
    path: path.resolve(__dirname, './dist'), // The package file path of the project
    publicPath: '/dist/'.// Access path through devServer
    filename: 'build.js' // The packaged file name
  },
  devServer: {
    historyApiFallback: true.overlay: true
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'}},module: {
     rules: [{test: /\.css$/.use: [
           'vue-style-loader'.'css-loader'],}, {// scss
         test: /\.scss$/.use: [
           'vue-style-loader'.'css-loader'.'sass-loader'],}, {// Add a loader that parses js
         test: /\.js$/.loader: 'babel-loader'.exclude: /node_modules/}}};Copy the code

At this point we modify main.js to try to use es6 syntax

// src/main.js
import Vue from 'vue';
// import Vue from 'vue/dist/vue.esm.js'  // 解决You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build


// console.log('hello world');

const say = function () {
  return new Promise((resolve, reject) = > {
    resolve('I am es6'); })}var app = new Vue({
  el: '#app'.data: {
    mess: 'Hello, [email protected]! '
  },
  methods: {
    updateData() {
      say().then((res) = >{
        this.mess = res;
      });
    },
    
  },
  created() {
    this.updateData(); }})Copy the code

The page output is as follows

import Vue from 'vue';
// import Vue from 'vue/dist/vue.esm.js'  // 解决You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build


// console.log('hello world');

const say = function () {
  return new Promise((resolve, reject) = > {
    resolve('I am es7'); })}var app = new Vue({
  el: '#app'.data: {
    mess: 'Hello, [email protected]! '
  },
  methods: {
    /*updateData() { say().then((res)=>{ this.mess = res; }); }, * /
    async updateData() {
      const mess = await say();
      this.mess = mess;
    }
  },
  created() {
    this.updateData(); }})Copy the code

The page is displayed as follows:

“ReferenceError: regeneratorRuntime is not defined”

In order to support ES7 syntax, you need to install dependencies for translation.

There are two scenarios
Plan a
npm i --save-dev babel-plugin-transform-runtime
Copy the code

Modify the. Babelrc file

// .babelrc
{
	"presets": [["env", { "modules": false}]."stage-3"]."plugins"https://www.jianshu.com/p/7a7f7abcddb5: [[/ / reference"transform-runtime",
		{
			"helpers": false."polyfill": false."regenerator": true."moduleName": "babel-runtime"}}]]Copy the code

Here’s a quick explanation of preset’s relationship to Babel:

  • Preset already includes a set of plug-ins for conversion of ES6+ syntax, and if only a few new features are used instead of most, just the corresponding conversion plug-in can be used instead of preset
  • By default, Babel only converts the syntax, not the new API. If you want to use the new API, you need to use the corresponding conversion plug-in or Polyfill

For example, Babel can convert arrow functions, class, and other syntaxes to ES5-compatible forms by default, but cannot convert new global objects such as Maps, sets, and Promises, so polyfill is needed to emulate these new features

The page output is normal:

Scheme 2

Global Babel – polyfill

npm i babel-polyfill --save-dev
Copy the code

Webpack.config. js is modified as follows

// webpack.config.js
  // Entry: './ SRC /main.js', // The entry file of the project, webpack will start from main.js and load and pack all dependent JS
  entry: ['babel-polyfill'.'./src/main.js']./ / entry documents of the project, can from main webpack js began, all depend on the js loading packaging reference https://www.jianshu.com/p/3b27dfc6785c
Copy the code

At this point, re-run the project NPM run dev result plan 1

Es6 and ES7 Translation section refer to the article several ways of using babel-polyfill

The article finally

Project construction, missing what fill what!! Check the complete address of the project @Wang Yino wLOVE_c/webPack4.0 +vue2.0

June 16, 2019 Article updates webPack agent configuration

The reason for this update was asked by a student in a technology sharing groupWebpack has been updated to 4.34.0. Some students do not know how to set the proxy, so I updated the proxy configuration with the help of this article.

Install dependencieswebpack-dev-server

 npm install webpack-dev-server --save-dev
Copy the code

In fact, Webpack uses HTTP-proxy-middleware as a direction proxy for cross-domain middleware, so if you’re interested, you can find out for yourself

Modify the configuration as follows

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

module.exports = {  / / module exports commonjs specification. devServer: {historyApiFallback: true.overlay: true.proxy: {
      '/api': {
        target: 'http://localhost:3000'.// Domain name and port of the interface If the port number is 80, you can skip this parameter
        pathRewrite: {'^/api' : ' '}, // If it does not start with API, it can be cleared
        changeOrigin: true.// Target is a domain name.
        secure: false.// By default, backend servers running over HTTPS with invalid certificates are not accepted. If you want to accept, modify the configuration as follows:}},},... };Copy the code

At this point you run project NPM run dev You will find that request to the/API/users will now be agent to request http://localhost:3000/api/users. And there will be no cross-domain problems! But the backend students to allow cross-domain or set the domain name whitelist Oh

For more webpack-dev-server configurations, go to @webpack/devserver-proxy

If you want to use nginx as a proxy, you can do so. For details please refer to my other article @Wang Yino Eno’s article nginx deployment/proxy/cross domain