preface

In the meantime, I’m free to write a few articles. Since I have no time to sort out the things I use now for a long time, I will slowly sort out some documents to record the work and life of the previous period.

The topic of this article is vuE-CLI understanding. Perhaps one of the problems many people find when developing vUE is that they just use it and don’t understand what’s in it. The current framework is good enough that developers don’t have to worry about setting up a development environment. But sometimes, we still have to go back to the original life experience, can make their own higher level, I hope we encourage each other. If you like my article, welcome to comment, welcome to Star~. Welcome to my Github blog

The body of the

First, let’s talk about installation. In the beginning and end of the purpose, or a few words hastily finished. The steps are as follows:

  • Install the vue – cli

    npm install vue-cli -g

  • Use the Webpack template to install the directory

    vue init webapck webpack-template

After that, we can open the directory using the IDE.

Note here my VUE-CLI version 2.9.2, so as not to mislead the reader after the revision.

After that, I attached the screenshot of my own directory without any changes, as shown in the picture:

First of all, the first question, where do we start? Of course, it starts with webpack.base.conf.js. This is something that both dev and Prod environments load. Then, we can start with a few files that will be used in webpack.base.conf.js. In fact, the following file is used in base, which we can see from the code:

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('.. /config')
const vueLoaderConfig = require('./vue-loader.conf')
Copy the code

Respectively is:

  • Path [path module]
  • Utils.js file in the build directory
  • Index file in the config directory
  • The vue-loader.conf.js file in the build directory

The path path

Nodejs is a file path retrieval and setting module. Nodejs is a file path retrieval and setting module. Nodejs is a file path retrieval module.

The path module provides utilities for handling file and directory paths

utils.js

We can go in there and look at the code, and we can actually infer from the name that it probably provides methods for the whole scaffold. We can start by looking at the resource file referenced by the header:

const path = require('path')
const config = require('.. /config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('.. /package.json')
Copy the code

It also references the path module and the index.js file in the config directory, followed by an NPM package — extract-text-webpack-plugin. This package is used to separate CSS and JS content. We can learn more about it later. It also references package.json, which is a JSON file that, when loaded, becomes an object.

So, we need to start with its head dependency:

The PATH module has been mentioned before, so we won’t go into details here. We can examine the index.js file in the config directory.

index.js

In this file, there are plenty of code comments that we can delve into as well.

From the code, we can see that we exported an object with two Settings dev and build through module.exports.

In dev, some configuration is set, with the following code:

modules.exports = {
	dev: {
	
	    // Paths
	    assetsSubDirectory: 'static'.assetsPublicPath: '/'.proxyTable: {},
	
	    // Various Dev Server settings
	    host: 'localhost'.// can be overwritten by process.env.HOST
	    port: 8080.// can be overwritten by process.env.PORT, if port is in use, a free one will be determined
	    autoOpenBrowser: false.errorOverlay: true.notifyOnErrors: true.poll: false.// https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
	
	    // Use Eslint Loader?
	    // If true, your code will be linted during bundling and
	    // linting errors and warnings will be shown in the console.
	    useEslint: true.// If true, eslint errors and warnings will also be shown in the error overlay
	    // in the browser.
	    showEslintErrorsInOverlay: false./** * Source Maps */
	
	    // https://webpack.js.org/configuration/devtool/#development
	    devtool: 'eval-source-map'.// If you have problems debugging vue-files in devtools,
	    // set this to false - it *may* help
	    // https://vue-loader.vuejs.org/en/options.html#cachebusting
	    cacheBusting: true.// CSS Sourcemaps off by default because relative paths are "buggy"
	    // with this option, according to the CSS-Loader README
	    // (https://github.com/webpack/css-loader#sourcemaps)
	    // In our experience, they generally work as expected,
	    // just be aware of this issue when enabling this option.
	    cssSourceMap: false,}}Copy the code

From its comments, we can understand that it configudes static paths, local server configuration items, Eslint, Source Maps, and other parameters in dev. If we need to change static resource files, server ports, etc. during development, we can do so in this file.

There is also a build object, which is a package of configurations when the VUE local server starts, as follows:

build: {
    // Template for index.html
    index: path.resolve(__dirname, '.. /dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '.. /dist'),
    assetsSubDirectory: 'static'.assetsPublicPath: '/'./** * Source Maps */

    productionSourceMap: true.// https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map'.// Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false.productionGzipExtensions: ['js'.'css'].// Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
Copy the code

This includes changes to template files, some path Settings after packing directories, gzip compression, etc. Once you understand what these fields mean, you can take the initiative to change the contents of the directory later in your development according to the needs of the project.

After talking about the index.js file in config, we can go back to the utils.js file and look at a few of these methods to see what they do.

  1. AssetsPath method

    Takes a _path argument

    Returns the static directory position concatenation path.

    It determines the current running environment based on the nodejs variable proccess.env.node_env. Returns different static directory locations under different environments to concatenate the given _path parameter.

  2. CssLoaders method

    It takes an options argument with attributes such as sourceMap and usePostCSS.

    Meanwhile, we use the extract-text-webpack-plugin we mentioned earlier to separate out the CSS code in JS and package it separately. At the same time, it returns an object containing CSS precompilers (less, Sass, stylus)loader generation methods, and so on. If your document explicitly requires only one CSS language, you can make the language a little clearer and reduce the size of the NPM package (which is a nuisance after all).

  3. StyleLoaders method

    The accepted options object is the same as the above method. This method simply generates different loaders based on the method configuration in cssLoaders. And then return it.

  4. CreateNotifierCallback method

    This invokes a module, available on GitHub, which is a nodeJS module that sends notifications on a native operating system. A function used to return scaffolding errors

There are four function methods defined in utils.

In the webpack.base.conf.js file, we can directly skip the index.js file in the config directory, which has been analyzed before. Take a look directly under vue-loader.conf.js.

vue-loader.conf.js

There’s very little code in this file, so we can just paste it in and analyze what it does. The code is as follows:

'use strict'
const utils = require('./utils')
const config = require('.. /config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
  ? config.build.productionSourceMap
  : config.dev.cssSourceMap

module.exports = {
  loaders: utils.cssLoaders({
    sourceMap: sourceMapEnabled,
    extract: isProduction
  }),
  cssSourceMap: sourceMapEnabled,
  cacheBusting: config.dev.cacheBusting,
  transformToRequire: {
    video: ['src'.'poster'].source: 'src'.img: 'src'.image: 'xlink:href'}}Copy the code

The sourceMap function will be enabled if the NODE_ENV variable is used in production environment. The sourceMap function will be enabled if the NODE_ENV variable is used in production environment. Add sourceMap functionality to cssLoaders later. Then determine if the cacheBusting property, which refers to cacheBusting, is set to false, especially when doing sourceMap debugging, which is very helpful. Finally, the content of a transformation request is configured with the attributes of video, source, IMG, image, etc.

Vue-loader is the loader for Webpack.

With all this analysis, I’m finally back in the webpack.base.conf.js file

webpack.base.conf.js

Eslint rules ();}} {{Eslint rules ();}}

Let’s go straight to the function behind, the createLintingRule method:

A formatter is loaded, which displays esLint’s rule errors on the terminal, allowing developers to directly locate the correct location and modify the code.

The next object is the basic configuration information for WebPack. We can analyze it field by field:

  • Context => The context of the running environment, which is the actual directory
  • Entry => Entry file: main.js file under SRC
  • Output => Output content. The internal configuration varies according to different operating environments
  • Resolve => The Extensions field specifies the file suffix to detect, and alias is used to specify the alias. In the reference file path, the alias symbol, if any, is replaced with the specified path.
  • Module => configures loader for esLint, Vue, JS, image resources, font ICONS, files, etc. See webpack’s official website for details.
  • Node => There are some comments here, mainly to prevent some of the default injection behavior of Webpack, because vUE already has these features.

After reading this, you probably get a glimpse of what’s in webapck.base.conf.js. In fact, understanding it also requires you to know webPack, a very useful packaging tool.

After that, we go back and forth with the webpack.dev.conf.js file

webpack.dev.conf.js

This file references the webapck-merge NPM package, which merges two configuration objects. The code is as follows:

const merge = require('webpack-merge');
const devWebpackConfig = merge(baseWebpackConfig, {
	...
}
Copy the code

This merges the WebPack configuration items in Base. After that, we can take a look at the new configuration items in the DEV environment and see what they do.

  1. First, add cssSourceMap functionality to The Rules of the Module

  2. Then there is DevTools, which, through the English translation of the annotations, shows that cheap-module-eval-source-map makes development faster.

  3. After that, it’s time for some configuration items for devSever. Packet block client error level, port, host and so on

  4. As well as new plugins, we can look at the actual new plugins(see the Webpack documentation for details) :

    • Define the process. The env
    • HotModuleReplacementPlugin: hot replacement plug-in module
    • NameModulesPlugin: displays the relative path of module loading plug-ins
    • NoEmitOnErrorsPlugin: In case of compilation errors, use NoEmitOnErrorsPlugin to skip the output phase. This ensures that the output resource does not contain errors
    • HtmlWebpackPlugin: Use the plugin to generate a specified template.

After that, there’s a function to make sure that when you start the program, if a port is occupied, you publish the new port through PortFinder, and then print the host string to run.

webpack.prod.conf.js

This is the file that will be packaged and used in the production environment. As you can see, it has fewer plug-ins and more plug-ins than the previous webapck.dev.conf.js file. We can also find out what it does by adding something to it as before! (The additions here are relative to what is not in webpack.dev.conf.js)

  1. New output configuration, we can see that it added some properties to output, package js into different chunks, and name them with hash suffix

  2. Some plug-ins have been added:

    • UglifJsPlugin: This is used to uglify JS code
    • ExtractTextplugin: Added some new properties, blocks and hash endings to packaged CSS files
    • OptimizeCssplugin: This plugin is used to optimize CSS files, mainly to compress CSS code
    • HashedModuleIdsPlugin: Ensure that the MODULE ID is stable
    • Optimize: Here’s a list of WebPack optimizations that you can see in the official documentation
    • CopyWebPlugins: Custom assets directory
  3. If gzip is not compressed, call the CompressionWebpackPlugin plugin to compress it

At this point, our WebPack configuration file is pretty much finished. Perhaps, will be a little confused, or see the official documents to the truth.

Finally, you need to analyze a build.js file.

build.js

This file will be used when packing.

First, the file begins by requesting functions in check-version.js, and then determines the node and NPM versions. In contrast to earlier versions of Node and NPM, warnings are generated during the packaging process. After that, set the environment parameters, set the production environment, and then a series of packaging processes.

conclusion

This article mainly summarizes some configuration parameters and the general function of the files generated by vue-CLI. I hope you can correct some mistakes. Meanwhile, I hope we can make progress together and encourage each other.

If you have any questions about what I wrote, you can comment on it. If I wrote something wrong, you are welcome to correct it. You like my blog, please follow me to Star~ yo github blog