1. Initialize the project

npm init -y
Copy the code

2. Install WebPack4 and webPack-CLI

npm i webpack@4 webpack-cli -D
Copy the code

3. Webpack4 configuration

After installing Webpack and webpack-CLI, create the webpack.config.js file in the project root directory and create the following:

const path = require("path"); const webpack = require("webpack"); const htmlWebpackPlugin = require("html-webpack-plugin"); Module.exports = {entry: path.resolve(__dirname, './ SRC /main.js'), // path: {path: Path.resolve (__dirname, './dist'), dist filename: Dist /static/bundle-[hash:8].js', dist/static publicPath: '/'}}Copy the code

4. Configure the Webpack4 package command

Configure the corresponding webpack command in scripts in package.json:

"build": "webpack --config ./webpack.config.js"
Copy the code

5. Create an entry file

Create a SRC directory under the root directory and create a main.js file under the SRC directory as the entry file for the entire project. This entry file is configured in the entry property of webpack.config.js.

6. Package projects

Open the terminal and enter NPM run build. After execution, the packaged file dist will be generated in the root directory. Open the dist directory and you can see the output file bundle.js configured in webpack.config.js. At this point, you have simply created a WebPack-based project. The next step is to get the project running.

Create a template file

Create index.html in the project root directory as follows:

<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <! -- <meta name="viewport" content="width=device-width,initial-scale=1.0"> --> <! --> <meta http-equiv="Expires" content="0"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Cache-control" content="no-cache"> <meta http-equiv="Cache" content="no-cache"> <link rel="shortcut icon" href="" type="image/x-icon"> <title>demo</title> <style> body, html { margin: 0; padding: 0; } </style> </head> <body> <div id="app"></div> <! -- built files will be auto injected --> </body> </html>Copy the code

8. Install htML-webpack-plugin

The html-webpack-plugin can automatically generate a packaged index.html(including various JS and CSS) according to the index.html of the project while it is running. As follows:

npm i html-webpack-plugin@4 -D
Copy the code

9. Configure WebPack

After the html-webpack-plugin is installed, in order to automatically generate the corresponding index.html after packaging, we need to implement the instance of htMl-webpack-plugin in webpack.config.js, using the index.html in the project root directory as the template. Automatically generates runnable index.html. Add the following code to webpack.config.js

Const htmlWebpackPlugin = require('html-webpack-plugin') // add html-webpack-plugin to plguins: [new htmlWebpackPlugin({// Can specify the file when the template lets this file read the template entry file template: Path.resolve (__dirname, '../index.html'), // output template file named index.html, filename: 'index.html'})]Copy the code

Save and execute NPM run build again. You can see the index. HTML file in the corresponding dist directory. Open the browser to index. HTML. But this requires manual packaging each time, and then open access. You can install webpack-dev-server for automatic packaging.

10. Install webpack-dev-server

Webpack-dev-server is the front-end development server. Webpack dev – server features:

  • Have Webpack do module packaging and handle resource requests for the resulting packaging
  • As a normal Web Server, it handles static resource file requests
  • Solve the NPM run build back and forth, and then update the code problem, more convenient
  • You can set port and open(automatic page opening). For more configuration, you can refer to the official website API
  • Auto refresh: Content automatically changed by the browser
npm i webpack-dev-server -D
Copy the code

After installation, webpack.config.js needs to be configured as follows:

devServer: { contentBase: path.resolve(__dirname, '.. Dist '), // serve files in dist to localhost:8888. Compress: true. // Compress: true. HistoryApiFallback: true, // Don't skip inline: Overlay: {warning: true, errors: true}, overlay: {warning: true, errors: true}, publicPath: '/' //Copy the code

After configuration, you need to configure the package.json development server startup command:

"scripts": {
    "dev": "webpack server --config ./webpack.config.js"
}
Copy the code

There is a warning here that lets us set mode, which has a default value, which can also be passed through the scripts command, via Node’s process.env. As follows:

"scripts": {
    "dev": "webpack server --mode=development --config ./webpack.config.js"
}
Copy the code

This will start the development server to run the project using NPM run dev.

Install the clean-webpack-plugin

Each time when packing, we always find that we need to delete the original package first, otherwise, we will increase the dist package. The clean-webpack-plugin can be used to remove the original Dist before each packaging. The clean-webpack-plugin defaults to delete all files in the path of the output configuration.

npm i clean-webpack-plugin -D
Copy the code

After the installation is complete, configure webpack.config.js and add the following code:

Const {CleanWebpackPlugin} = require(' cleanwebpack-plugin ') //Copy the code

12. Install the Babel plugin Install ue-loader, URL-loader, file-loader, style-loader, CSS-loader, sass-loader, Node-sass, autoprefixer, postCSs-loader, ue-templa te-compiler

12.1. Install the Babel plug-in and configure the. Babelrc file

Before using Vue, you need to install the Babel plug-in. This is because the current browser does not support es5 or higher standard syntax. You need to use Babel to compile the advanced syntax into the syntax that the current browser can execute. Webpack needs to be installed above @babel/core@7, babel-loader@8. @babel/plugin-transform-runtime, @babel/preset-env, @babel/ Runtime, @babel/runtime-corejs2, @babel/plugin-syntax-dynamic-import is a plug-in that dynamically imports dependencies, and babel-plugin-component is a plug-in needed to introduce element-UI on demand. Core-js is a fully modular javascript standard library.

npm i @babel/core@7 babel-loader@8 @babel/plugin-transform-runtime @babel/preset-env @babel/runtime @babel/runtime-corejs2 @babel/plugin-syntax-dynamic-import babel-plugin-component core-js@2 -D
Copy the code

After the installation is complete, create a.babelrc file in the project root directory and add the following:

//" presets": [["@babel/preset-env", {"useBuiltIns": "usage", //"corejs": presets": [["@babel/preset-env", {"useBuiltIns": "usage", // 3, // NPM I --save-dev core-js@3 "corejs": 2, // NPM I --save-dev core-js@2 "modules":false }], "plugins": [["@babel/ transform-runtime", {"helpers": true, "regenerator": true, "useESModules": true, "corejs": 2 } ], "@babel/plugin-syntax-dynamic-import", [ "component", { "libraryName": "element-ui", "styleLibraryName": "theme-chalk" } ] ] }Copy the code

Add the following code to webpack.config.js:

Module: {rules: [{test: / \. Js | x $/, use: [' Babel - loader '], exclude: / node_modules / / / not compiled code under the node_modules}]}Copy the code

12.2 Install vuE-Loader and VUe-template-Compiler

Vue-loader is a vUE translator. Only when it is installed can a project recognize vUE files and translate them. Vue – template-Compiler This module can be used to precompile Vue 2.0 templates into rendering functions (template => ast => render) to avoid runtime compilation overhead and CSP constraints. In most scenarios, vue-Loader is used with vue-template-Compiler. It is only needed to write build tools with very specific requirements. The version of VUE must be consistent with vue-template-Compiler.

npm i vue-loader vue-template-compiler -D
Copy the code

Once installed, you need to configure it in webpack.config.js. Add the following code to the Module. exports object:

const VueLoaderPlugin = require('vue-loader/lib/plugin');
module: {
    rules: [
        {
            test: /\.vue$/,
            use: ['vue-loader']
        }
    ]
},
plugins: [
    new VueLoaderPlugin()
]
Copy the code

12.3. Install url-loader and file-loader

Url-loader is a plug-in used to process images, fonts, media and other types of files. If it is not configured, these types of resources cannot be correctly identified after the project is packaged and run. Url-loader contains some functions of file-loader. Therefore, if the limit on files does not reach the limit, you do not need to configure file-loader separately.

npm i url-loader file-loader -D
Copy the code

Once installed, you need to add the following code to webpack.config.js:

module: { rules: [ { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, use: [{ loader: 'url-loader', options: { esModule: [Object Module] Limit: 10000, name: 'images / [name] - [8] hash: [ext]', / / belongs to the attribute of the file - loader}}}, {test: / \. (mp4 | webm | | ogg mp3 | wav | flac | aac) (\? *)? $/, use: [{loader: 'url-loader', options: {esModule: false, // set this to false limit: 10000, name: 'media/[name].[hash:7].[ext]' } } ] }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: "url-loader", options: {esModule: false, // set this to false limit: 10000, // size <= 5KB name: "Fonts / [name] - [hash: 7]. Min. (ext)", / / belongs to the attribute of the file - loader]}}}Copy the code

12.4. Install style-loader, CSS-loader, Sass-loader, Node-sass, autoprefixer, and postCSS-loader

The autoprefixer plugin is used to automatically prefix CSS code with the corresponding browser. Postcss-loader is used to parse CSS into an abstract syntax tree and call plug-ins to process the abstract syntax tree and add functionality. CSS -loader is used to parse the CSS code in the code, style-loader is used to mount the code parsed by CSS -loader to the HTML page. Node-sass is a sass library. You can use the sASS syntax by using lang=” SCSS “in the project style note. Sass-loader is the compiler for Node-sass. Because of the use of Element-UI in the project, both plug-ins must be installed

npm i style-loader css-loader sass-loader node-sass autoprefixer@9 postcss-loader@4 -D
Copy the code

Once installed, add the following code to webpack.config.js:

module: { rules: [ { test: /\.(c|le)ss$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'postcss-loader', options: { sourceMap: true, postcssOptions: { plugins: [["autoprefixer", {// options},],]}}}]}]}Copy the code

At this point, you have configured the basic environment required for VUE development. Next, you can install the VUE family bucket and configure it for development.

13. Install vUE family barrel

Vue bucket includes VUE, VUE-Router, and VUEX. For details, please visit the vUE official website.

npm i vue vue-router vuex -S
Copy the code

After the installation, create the views, Router, and Store directories in the root directory of the project. Then create index.js in each directory and edit main.js:

import Vue from 'vue'
import App from './App.vue'
import Route from './router/index'
import Store from './store/index'

new Vue({
    el:"#app",
    router: Route,
    store: Store,
    render:(h)=>h(App)
})
Copy the code

Create a new app. vue file in the SRC directory and add the following code:

<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>
export default {
  name: 'App'
}
</script>
<style scoped>
</style>
Copy the code

Add the following code to the index.js file in the router directory:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router);

cosnt routes = []

const router = new Router({
    routes: routes
});

export default router;
Copy the code

Add the following code to the index.js file in the store directory:

import Vue from 'vue'
import Vuex from 'vuex'

import user from './user/index'

Vue.use(Vuex);

const store = new Vuex.Store({
    modules: {
        user
    }
})

export default store
Copy the code

14. Configure webpack.config.js

Configure the directory alias. Configure the file extension so that you do not need to write the file extension when importing files. Add the following code to webpack.config.js:

module.exports = { ... Alias: {'vue ': alias: {'vue$': alias: {'vue$': 'vue/dist/vue. Esm. Js', / / introduction of the vue' @ ': path. Resolve (__dirname,'.. /src') } } ... }Copy the code

Install element-UI

Element-ui is an open source UI framework for Me

npm i element-ui -S
Copy the code

Finally, the complete webpack.config.js file is attached

const path = require("path"); const webpack = require("webpack"); const htmlWebpackPlugin = require("html-webpack-plugin"); const VueLoaderPlugin = require('vue-loader/lib/plugin'); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); module.exports = { entry: path.resolve(__dirname, './src/main.js'), output: { path: path.resolve(__dirname, './dist'), filename: './static/bundle-[hash:8].js', publicPath: '/' }, devServer: { open: true, hot: true, port: 8889 }, module: { rules: [ { test: /\.js|x$/, use: ['babel-loader'], exclude: /node_modules/ }, { test: /\.vue$/, use: ['vue-loader'] }, { test: /\.c|(sc)ss$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'sass-loader' }, { loader: 'postcss-loader', options: {sourceMap: true, postcssOptions: {plugins: [["autoprefixer", {// options},],]}}}]}, {test: / \. (PNG | jpe? G | | GIF SVG) (\? *)? $/, use: [{loader: 'url - loader, the options: {esModule: false, / / here set to false limit: 10000, name: 'images / [name] - [8] hash: [ext]', / / belongs to the attribute of the file - loader}}}, {test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, use: [ { loader: 'url-loader', options: { esModule: False, // set false limit: 10000, name: 'media/[name].[hash:7]. / \. (woff2? | eot | the vera.ttf | otf) (\? *)? $/, loader: "url - loader," options: {esModule: false, / / here set to false limit: Fonts /[name]-[hash:7].min.[ext]", // fonts/[hash:7].min.[ext]", [ new htmlWebpackPlugin({ template: path.resolve(__dirname, './index.html'), filename: path.resolve(__dirname, './dist/index.html') }), new CleanWebpackPlugin(), new VueLoaderPlugin() ] }Copy the code