The preparatory work

preface

For some reason, I had to finish a demo. After thinking about it, I decided to build a simple scaffolding for VEU’s SPA project. Basic concepts for webpack (entry, the output, loader, the plugin, mode…). Have the understanding, but have not tried to lift scaffolding friends can continue to look down.

The preparatory work

The Node environment is required, of course

Let’s start

Mkdir im-chat-vue // create a file project folder. The demo name is im-chat-vue

mkdir build //

mkdir src //

NPM init // creates package.json and initializes it

Dependencies required by the installation

NPM install –save-dev vue Not much is introduced

NPM install –save-dev webpack // Not much is introduced

NPM install –save-dev webpack-cli //webpack version 4+

The NPM install –save-dev path //path module provides utility functions for handling file and directory paths.

NPM install –save-dev html-webpack-plugin // Simplifies HTML file creation plugin that simplifies HTML files to serve your bundles

NPM install –save-dev clean-webpack-plugin // A webpack plugin to remove/clean your build folder(s) before building

NPM install –save-dev vue-loader // vue.js component loader

NPM install –save-dev vue-template-compiler // Works with vue-loader for template function compilation

NPM install –save-dev webpack-dev-server // Hot update requires setting up the service module

NPM install –save-dev style-loader CSS-loader // CSS style processor

After the installation is complete we create two files in the SRC directory app.vue; main.js

src/app.vue

<template lang="html">
    <div class='test'>
        <p class="test">IM-chat-vue  IM-chat-vue  </p>
        {{test}}
    </div>
</template>

<script>
    export default {
        data(){
            return {
                test:"Simply Build vue scaffolding Project"}}}</script>

<style>
    .test{
        color:red;
    }
</style>
Copy the code

src/main.js

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

new Vue({
    el:'#app'.render: h= > h(App)
})

Copy the code

index.html


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>webpack app</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
Copy the code

This is where the VUE comes in – now let’s configure WebPack to compile and package the Vue project

Create webpack.config.js and the code in the build folder you just created

const path = require('path');    // The path module provides utility functions for handling file and directory paths.
const HtmlWebpackPlugin = require('html-webpack-plugin');   // Build the HTML file
const { CleanWebpackPlugin } = require('clean-webpack-plugin');  // Clean up the files in the build directory
const webpack = require('webpack');       // Webpack
const VueLoaderPlugin = require('vue-loader/lib/plugin');         // vue-loader compiles vue files
module.exports = {
    mode: "development".entry: {       / / the entry
        "app": path.resolve(__dirname, ". /.. /src/main.js")},module: {// Handle different types of modules in the project.
        rules:[      Each rule can be divided into three parts - condition, result and nested rule.
            {
                test:/\.css/.use: ['style-loader'.'css-loader']   // style-loader and CSS-loader compile CSS processing
            },
            {
                test: /\.vue$/.loader: 'vue-loader'         //vue-loader compiles the vue module}},devtool: 'inline-source-map'.// Map mapping code to facilitate error query
    devServer:{
        contentBase: './dist'.// Tell the service where to supply the code content (static files are used this way)
        hot:true    // Hot mode is enabled
    },
    plugins: [new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({            / / build HTML
            filename:'index.html'./ / file name
            title:'im-chat-vue'.//title
            template:'./index.html'.// Follow the template style
        }),
        new webpack.HotModuleReplacementPlugin(),  // Hot module replacement is enabled
        new VueLoaderPlugin()                 // Vue-loader plug-in is enabled].output: {        / / export
        filename: 'index.js'./ / file name
        path: path.resolve(__dirname, '.. /dist'),   / / path
        publicPath:""        //srcript import path
    },
    resolve: {// Import path does not need to write the corresponding suffix
        extensions: ['.js'.'.vue'.'.json'].alias: {// We are using the runtime version of vue, and the compiler in this version is not available, we need to switch it to the runtime + compiled version
            'vue$':'vue/dist/vue.esm.js'.// direct to SRC with @
            The '@': path.resolve(__dirname,'./src'),}}};Copy the code

With the above steps completed we can start adding script commands to package.json

{
  "name": "im-chat-vue"."version": "1.0.0"."description": ""."main": "main.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack --config=build/webpack.config.js"
  },
  "author": "ruindong"."license": "ISC"."devDependencies": {
    "clean-webpack-plugin": "^ 3.0.0"."css-loader": "^ 3.2.0"."html-webpack-plugin": "^ 3.2.0"."path": "^ 0.12.7"."style-loader": "^ 1.0.0"."vue": "^ 2.6.10"."vue-loader": "^ 15.7.1"."vue-template-compiler": "^ 2.6.10"."webpack": "^ 4.41.2"."webpack-cli": "^ 3.3.10"."webpack-dev-server": "^ 3.9.0"}}Copy the code

Then execute NPM run build and the build succeeds. At the same time, the dist file is generated under the figure

Open the index.html file in your browser as shown

At this point a simple scaffolding for compiling and packaging the VUE project is complete. But that’s not enough. We also need a lot of assistance in development, such as hot updates.

The hot update code is already configured in webpack.config.js. So you just need to modify package.json and add the script command to start hot update

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

Then run NPM dev and the hot update will compile successfully. Modification code can now synchronize hot updates on web pages

At this point a simple scaffolding is complete. Is it easier than you think

Now it’s time to do scaffolding for pre-compiled CSS. And CSS separation

I prefer to use less, so I only introduce less loadder handling here

npm install –save-dev less

npm install –save-dev less-loader; npm install extract-text-webpack-plugin –save-dev

// Install less and the necessary less-loader(less compilers to CSS);

module: {// Handle different types of modules in the project.
        rules:[      Each rule can be divided into three parts - condition, result and nested rule.
            {
                test:/\.css/.use: ['style-loader'.'css-loader']   // style-loader and CSS-loader compile CSS processing
            },
            {
                test: /\.vue$/.loader: 'vue-loader'         //vue-loader compiles the vue module
            },
            {
                test:/\.less/.use: ['style-loader'.'css-loader'.'less-loader'] // Compile Less to CSS}},Copy the code

NPM install –save-dev extract — text-webpack-plugin // Webpack4 is deprecated

NPM install –save-dev MiniCssExtractPlugin // Use this to extract CSS

Postcss-loader and autoprefixer are required to install postcss.config.js in the root directory to automatically handle CSS3 attribute prefixes

// postcss.config.js
module.exports = {
    plugins: {
        'autoprefixer': {
            overrideBrowserslist: [
                "Android 4.1"."iOS 7.1"."Chrome > 31"."ff > 31"."ie >= 8"]},// 'postcss-pxtorem': {
        / / rootValue: 37.5.
        // propList: ['*']
        // use it again if necessary}}Copy the code
// build/webpack.config.js
const path = require('path');    // The path module provides utility functions for handling file and directory paths.
const HtmlWebpackPlugin = require('html-webpack-plugin');   // Build the HTML file
const { CleanWebpackPlugin } = require('clean-webpack-plugin');  // Clean up the files in the build directory
const webpack = require('webpack');       // Webpack
const VueLoaderPlugin = require('vue-loader/lib/plugin');         // vue-loader compiles vue files
//const ExtractTextPlugin = require("extract-text-webpack-plugin"); // CSS split webpack4 is no longer supported
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); / / CSS separation

module.exports = {
    mode: "development".entry: {       / / the entry
        "app": path.resolve(__dirname, ".. /src/main.js")},module: {// Handle different types of modules in the project.
        rules:[      Each rule can be divided into three parts - condition, result and nested rule.
            {
                test: /\.(sa|sc|le|c)ss$/.use: [
                    'style-loader',
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            hmr: true,}},'css-loader'.'less-loader',
                    {
                        loader: 'postcss-loader'.options: {
                            config: { path: path.resolve(__dirname, '.. /postcss.config.js'}},}],}, {test: /\.vue$/.loader: 'vue-loader'         //vue-loader compiles the vue module}},devtool: 'inline-source-map'.// Map mapping code to facilitate error query
    devServer:{
        contentBase: path.resolve(__dirname, '.. /dist'),    // Tell the service where to supply the code content (static files are used this way)
        hot:true    // Hot mode is enabled
    },
    plugins: [new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({            / / build HTML
            filename:'index.html'./ / file name
            title:'im-chat-vue'.//title
            template:'index.html'.// Follow the template style
        }),
        new webpack.HotModuleReplacementPlugin(),  // Hot module replacement is enabled
        new VueLoaderPlugin(),                 // Vue-loader plug-in is enabled
        // New ExtractTextPlugin("index.css") // Configure the isolated CSS file address webpack4 is no longer used
        new MiniCssExtractPlugin({
            // The configuration like webpackOptions.output can be ignored
            filename: 'css/[name].css'.//chunkFilename: 'css/[id].css',})].output: {        / / export
        filename: 'index.js'./ / file name
        path: path.resolve(__dirname, '.. /dist'),   / / path
        publicPath:""        //srcript import path
    },
    resolve: {// Import path does not need to write the corresponding suffix
        extensions: ['.js'.'.vue'.'.json'].alias: {// We are using the runtime version of vue, and the compiler in this version is not available, we need to switch it to the runtime + compiled version
            'vue$':'vue/dist/vue.esm.js'.// direct to SRC with @
            The '@': path.resolve(__dirname,'.. /src'),}}};Copy the code

The CSS of the operation page of the above steps is shown in the figure

The compiled result is shown below

Page CSS has been removed and supports less. There are also auto-add browser prefixes

Processing image path

npm install –save-dev file-loader url-loader

Install Babel

npm install –save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react

Next configure the scaffolding environment. I already saw some thumbs up. I continue to update. The current time is 9:30 am on November 5, 2019. The configuration environment and ESLint, VUe-Router and status controller will be updated later.