preface

Recently, I am summarizing and deepening my knowledge, and then trying to build a complete Webpack + VUE project from scratch. Then through the project on the overall process of a summary, the article will be quite long, sub upload it, content is currently doing background projects as an example object, published some personal summary of things, I hope to be of some help to you. Of course, the same words, everyone’s understanding of the concept of different, but also hope to be able to point out the insufficiency of the supplement.

The body of the

Use WebPack to initialize the build project

1. Generate package.json file

npm init

2. Install webpack

NPM install -g webpack Global install NPM install –save-dev Webpack is installed in a local project

3. Preliminary construction of the project structure














  1. Preliminary understanding of webpack configuration rules about webpack configuration rules, here is a preliminary understanding of the meaning and usage of several commonly used attributes, the specific content does not need too much attention, mainly to understand the role of attributes
      const path = require('path');
      const webpack = require('webpack'); Const {CleanWebpackPlugin} = require(const {CleanWebpackPlugin} = require("clean-webpack-plugin"); Const VueLoaderPlugin = require(const VueLoaderPlugin = require('vue-loader/lib/plugin'); Const HtmlWebpackPlugin = require(const HtmlWebpackPlugin = require('html-webpack-plugin'); Module.exports = {// exports, the starting point or the starting point of an application. From this starting point, the application starts execution. If you pass an array, then each item in the array is executed. // Each HTML page has an entry point. Single-page application (SPA) : one entry point, multi-page application (MPA) : multiple entry points. // Generally points to the main.js file entry in the SRC directory of the project :{app:'./src/main.js'}, // Output, which tells WebPack how to export and where to export your "bundles, assets, and anything else you pack or load with WebPack" // Refers to the name and location of the generated files packed by WebPack. Output :{// Combine all dependent modules into a bundle.js file named filename:'bundle.js'// Output filename for each name:'[name].[hash].js'Path :path.join(__dirname,'./dist'}, // This property is used to set the processing rules corresponding to different types of modules in the project, that is, some of the sass,less, CSS, vue, images, files are set in this property, of course, Module: {rules: [{rules: [{testVue file use: [{// Loader used to convert the file type, loader:'vue-loader', options: {// Internal configuration loaders: {'scss': 'style-loader! css-loader! sass-loader'}}}],}, {test: /\.css$/,
                    use: ['vue-style-loader'.'css-loader'] // Use vue-style-loader to insert style tags}, {test: /\.(eot|svg|ttf|woff|woff2)(\? \S*)? $/, loader:'file-loader'
                  },
                  {
                    test: /\. SCSS $/, // Use: ['style-loader'.'css-loader'.'sass-loader'[}]}, // Customize the WebPack build process. For example, when multiple bundles share some of the same dependencies, using CommonsChunkPlugin helps extract these dependencies into the shared bundle. [new HtmlWebpackPlugin({template:'index.html',
                  filename:'index.html'}), new VueLoaderPlugin (), new webpack. HashedModuleIdsPlugin (), new CleanWebpackPlugin ()], / / how to configure modules is resolved, Resolve: {// The extension of auto-completion: ['.js'.'.vue'.'.json'], // Default path proxy // for example, import Vue from'vue', will automatically arrive'vue/dist/vue.common.js'This will save you from having to focus on different levels of concern when referencing files later in your development projectalias: {
                  The '@': path.join(__dirname, '/'.'src'),
                  '@api': path.join(__dirname, '/'.'src/api'),
                  '@styles': path.join(__dirname, '/'.'src/styles'),
                  '@config': path.join(__dirname, '/'.'config'),
                  'vue$': 'vue/dist/vue.common.js'.'@components':path.join(__dirname, '/'.'src/components')}}}Copy the code
  1. Preliminary start-up project

    1. First, improve the internal code of index.html
      <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <script SRC ="/dist/build.js"></script> </body> </ HTML >Copy the code
    2. Create the main.js file for the main entry in the SRC directory, and create a demo
    export default function say() {
        console.log('hello world');
    }
    Copy the code

    The main js file

    import say from './util';
    say();
    Copy the code
    1. After the basic information processing is complete, it is necessary to initially configure the WebPack file, which is simply equipped with an exit and entrance
    var path = require('path');
    var webpack = require('webpack');
    
    module.exports = {
        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}};Copy the code
    1. To start, we need to modify package.json. Add two startup commands called package.json
      "scripts": {
        // webpack-dev-server automatically starts a static resource Web server -- the hot parameter indicates that hot updates are enabled
        "dev": "webpack-dev-server --open --hot"."build": "webpack --progress --hide-modules"
      },
    Copy the code
    1. NPM run dev, you can start the project initially, and then modify util.js as you like. You can see that the browser will refresh automatically, which is very convenient. If you need to see the bundle.js file, You can execute NPM run build and see the generated bundle.js in the dist folder.
  2. The introduction of vue

    1. First, install vUE,

      npm i vue --save

    2. Then modify the main.js and index.html files, as well as the webpack.config.js file main.js

    import Vue from 'vue';
    
    var app = new Vue({
      el: '#app'.data: {
        message: 'Hello Vue! '}});Copy the code

    index.html

    <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <div id="app"> {{message}} </div> <script src="/dist/build.js"></script> </body> </html>Copy the code

    webpack.config.js

      var path = require('path');
      var webpack = require('webpack');
    
      module.exports = {
          entry: './src/main.js'.output: {
              path: path.resolve(__dirname, './dist'),
              publicPath: '/dist/'.filename: 'build.js'
          },
          devServer: {
              historyApiFallback: true.overlay: true
          },
          resolve: {
              alias: {
                // Add the identification path
                  'vue$': 'vue/dist/vue.esm.js'}}};Copy the code

    At this point, rerun NPM run dev and you’re done.

  3. Introduce SCSS and CSS

    1. Install the loader

      npm i node-sass css-loader vue-style-loader sass-loader --save-dev
    2. Modify the webpack. Config. Js
    var path = require('path');
    var webpack = require('webpack');
    
    module.exports = {
        entry: './src/main.js'.output: {
            path: path.resolve(__dirname, './dist'),
            publicPath: '/dist/'.filename: 'build.js'
        },
        devServer: {
            historyApiFallback: true.overlay: true
        },
        resolve: {
            alias: {
                'vue$': 'vue/dist/vue.esm.js'}},module: {
            rules: [{test: /\.css$/.// Matches a file with the suffix CSS
                    use: [ // Use css-loader and vue-style-loader respectively
                    // The parser is executed from bottom up (csS-loader followed by vue-style-loader)
                    // We use vue style-loader, otherwise we use style-loader
                        'vue-style-loader'.'css-loader'],},// Do the following
                {
                test: /\.scss$/.use: [
                    'vue-style-loader'.'css-loader'.'sass-loader'],}, {test: /\.sass$/.use: [
                        'vue-style-loader'.'css-loader'.'sass-loader? indentedSyntax'],}]}};Copy the code
    1. Create a style folder under SRC, create common.scss, write a style, and then import common.js in main.js
    body {
        background: #fed;
    }
    Copy the code

    main.js import ‘./style/common.scss’; Of course, when importing the file, we can configure the import rule in resolve in webpack.config.js as mentioned above

    resolve: {
            alias: {
              // Add the identification path
                'vue$': 'vue/dist/vue.esm.js'.'@style': path.join(__dirname, '/'.'src/style'),}}Copy the code

    Once configured, you can directly introduce @style/common.scss to point to the correct file, which can be useful in projects

8. Using Babel transcoding, you can transcode ES6 to ES5 syntax so that you can use the latest features in your project

  1. Install NPM I babel-core babel-loader babel-preset-env babel-stage-3 –save-dev 2. Create a new.babelrc file in the project root directory, write the contents, and add a loader.babelrc file to webpack.config.js

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

    webpack.config.js

    . {test: /\.js$/.loader: 'babel-loader'.// exclude excludes the files in the node_modules folder without transcoding
          exclude: /node_modules/
      }
    Copy the code
    1. Install babel-Polyfill and modify the entry to webpack.config.js

    NPM I babel-polyfill –save-dev changes webpack.config.js

    entry: ['babel-polyfill'.'./src/main.js'].Copy the code

    This allows you to test async, await, etc. es6 syntax.

  2. NPM I file-loader –save-dev then add a loader

{
  test: /\.(png|jpg|gif|svg)$/.loader: 'file-loader'.options: {
      name: '[name].[ext]? [hash]'}}Copy the code
  1. DevServer, in the course of daily development, often needs to be co-tuned with multi-party back-end development, which requires some urls to be proxy
   module.exports = {
   //...
       devServer: {
           proxy: {
           '/api': {
               target: 'http://localhost:3000',
               pathRewrite: {'^/api' : ' '}},'/bff': {
               target: 'http://localhost:3020',
               pathRewrite: {'^/bff' : ' '}},}}};Copy the code

This did not elaborate, put a link to know more about you can click on view at https://www.jianshu.com/p/f489e7764cb8

Vue – Single file component

1. Install vue-loader and add vue-loader NPM I vue-loader vue-template-compiler –save-dev webpack.config.js To add a loader

    {
      test: /\.vue$/,
      loader: 'vue-loader',
      options: {
          loaders: {
              'scss': [
                  'vue-style-loader'.'css-loader'.'sass-loader'].'sass': [
                  'vue-style-loader'.'css-loader'.'sass-loader? indentedSyntax']}}}Copy the code
  1. Create a new app.vue in the SRC directory
<template>
  <div id="app">
    <h1>{{ msg }}</h1>
    <img src="./img/logo.png">
    <input type="text" v-model="msg">
  </div>
</template>

<script>

import getData from './util';

export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js'
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      const data = await getData();
      this.msg = data; }}}</script>

<style lang="scss">#app { font-family: "Avenir", Helvetica, Arial, sans-serif; h1 { color: green; }}</style>
Copy the code

main.js

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

import './style/common.scss';

new Vue({
  el: '#app'.template: '<App/>'.components: { App }
})
Copy the code

index.html

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title>Document</title> </head> <body> <div id="app"></div> <script src="/dist/build.js"></script> </body> </html>Copy the code

source-map

Debugging is also an important requirement during the development phase. Source-map builds a bridge between pre-processing code and post-processing code. The main purpose is to facilitate the error location of developers. The processing operations here include: I) compress, reduce the size, II) merge multiple files into the same file, and III) compile other languages into javascript, such as TypeScript and CoffeeScript, and modify webpack.config.js

module.exports = {
    entry: ['babel-polyfill'.'./src/main.js'].// omit other...

    devtool: '#eval-source-map'
}; 
Copy the code

Packaging releases

  1. Installation of cross – env

    npm i cross-env --save-dev
  2. Modify the package. The json
"scripts": {
  "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot"."build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
}
Copy the code

Modify webpack.config.js to compress the js code if NODE_ENV is production

var path = require('path');
var webpack = require('webpack');

module.exports = {
    / / to omit...
}

if (process.env.NODE_ENV === 'production') {
    module.exports.devtool = '#source-map';
    module.exports.plugins = (module.exports.plugins || []).concat([
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: '"production"'}}),new webpack.optimize.UglifyJsPlugin(),
    ])
  }
Copy the code

At the end

In this way, a basic Webpack + Vue project is set up. In fact, there are many similar articles, and there are ready-made scaffolding to build, but this article is a basic article, not too big technical points. However, as a front-end engineer, how also need to have a basic document from scratch for later forgot reference, ha ha, well, not too much, I hope to be able to help you some friends. And finally, as usual, come on, everybody!