Home Web Front-end JS Tutorial Detailed explanation of the use of vue-cli

Detailed explanation of the use of vue-cli

May 15, 2018 am 10:24 AM
vue-cli use Detailed explanation

This time I will bring you a detailed explanation of the use of vue-cli. What are the precautions when using vue-cli? The following is a practical case, let's take a look.

vue-cli

Before development, we must read through the vue official documents and API at least once (reading the official documents is the most important, better than reading fifty or a hundred blogs). If you have good English reading skills, it is recommended to read the English documents. The content of the Chinese documents will be If you are a little behind, you have to read through the relevant vue-router, axios, vuex, etc.

Generally speaking, we first use vue-cli to build the basic structure of the project.

text

First, let’s talk about the installation stuff! For the purpose of having a beginning and an end, it’s still a matter of haste with a few words. Proceed as follows:

Install vue-cli

npm install vue-cli -g
Copy after login

Install directory with webpack template

vue init webapck webpack-template
Copy after login

After this, we can use the IDE to open the directory.

Indicate my vue-cli version 2.9.2 here to avoid misleading readers after subsequent revisions.

First of all, the first question, where to start? Of course, we started with webpack.base.conf.js. This is something that both the dev and prod environments will load. Then, we can start with several files that will be used in webpack.base.conf.js. In fact, the following files are used in base, 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 after login

They are:

  • path [Path module]

  • The utils.js file in the build directory

  • The index file in the config directory

  • vue-loader.conf.js file in the build directory

path path

This module can be introduced on the nodejs official website. In fact, it is a module for obtaining and setting file paths. When learning node, we often see this module being used extensively.

The path module provides tools for processing file and directory paths

utils.js

We can go there and take a look at the code. In fact, we can infer from the name alone that it may provide methods for the entire scaffolding. We can first take a look at the resource files 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 after login

Similarly, 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 the content of css and js. We can learn more about it later. At the same time, it also refers to the package.json file, which is a json file. After loading, it will become an object.

Therefore, we need to start with its head dependencies:

We have mentioned the path module before, so we won’t go into details here. We can analyze the index.js file in the config directory.

index.js

There are actually quite sufficient code comments in this file, and we can also delve into it.

From the code, we can see that an object is exported via module.exports, which contains the two settings dev and build.

In dev, some configurations are set, the code is as follows:

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 after login

Through its comments, we can understand that it configures static paths, local server configuration items, Eslint, Source Maps and other parameters in dev. If we need to change static resource files, server ports and other settings during development, we can modify them in this file.

There is also a build object below, which is some configuration packaged when the vue local server is started. The code is 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 after login

This includes modification of template files, some path settings after packaging the directory, gzip compression, etc. After understanding the meaning of these fields, you can proactively change the directory content according to project requirements in subsequent development.

After talking about the index.js file under config, back to the utils.js file, we can look at a few of the methods to analyze what roles they play.

1. assetsPath method

Accepts a _path parameter

返回static目录位置拼接的路径。

它根据nodejs的proccess.env.NODE_ENV变量,来判断当前运行的环境。返回不同环境下面的不同static目录位置拼接给定的_path参数。

2、cssLoaders方法

接受一个options参数,参数还有的属性:sourceMap、usePostCSS。

同时,这里用到了我们之前提到的extract-text-webpack-plugin插件,来分离出js中的css代码,然后分别进行打包。同时,它返回一个对象,其中包含了css预编译器(less、sass、stylus)loader生成方法等。如果你的文档明确只需要一门css语言,那么可以稍微清楚一些语言,同时可以减少npm包的大小(毕竟这是一个令人烦躁的东西)。

3、styleLoaders方法

接受的options对象和上面的方法一致。该方法只是根据cssLoaders中的方法配置,生成不同loaders。然后将其返回。

4、createNotifierCallback方法

此处调用了一个模块,可以在GitHub上找到,它是一个原生的操作系统上发送通知的nodeJS模块。用于返回脚手架错误的函数

一共这么四个函数方法,在utils中被定义到。

回看到webpack.base.conf.js文件中,我们可以直接跳过config目录下的index.js文件,之前已经分析过了。直接来看一下vue-loader.conf.js下的内容。

vue-loader.conf.js

这个文件中的代码非常的少,我们可以直接贴上代码,然后来分析,其中的作用。代码如下:

'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 after login

其中,主要就是根据NODE_ENV这个变量,然后分析是否是生产环境,然后将根据不同的环境来加载,不同的环境,来判断是否开启了sourceMap的功能。方便之后在cssLoaders中加上sourceMap功能。然后判断是否设置了cacheBusting属性,它指的是缓存破坏,特别是进行sourceMap debug时,设置成false是非常有帮助的。最后就是一个转化请求的内容,video、source、img、image等的属性进行配置。

具体的还是需要去了解vue-loader这个webpack的loader加载器。

分析了这么多,最终回到webpack.base.conf.js文件中

webpack.base.conf.js

其实的两个方法,其中一个是来合并path路径的,另一个是加载Eslint的rules的。

我们直接看后面那个函数,createLintingRule方法:

其中,加载了一个formatter,这个可以在终端中显示eslint的规则错误,方便开发者直接找到相应的位置,然后修改代码。

之后的一个对象,就是webpack的基础配置信息。我们可以逐一字段进行分析:

  • context => 运行环境的上下文,就是实际的目录

  • entry => 入口文件:src下的main.js文件

  • output => 输出内容,这内部的配置会根据不同的运行环境来进行变化

  • resolve => 其中的extensions字段,指定检测的文件后缀,同时alias是用于指定别名的。在引用文件路径中,如果有别名的符号,会被替换成指定的路径。

  • module => 配置了一些eslint、vue、js、图片资源、字体图标、文件等加载的loader。详细的可以去看webpack的官方网站。

  • node => 此处部分有注释,主要是阻止一些webpack的默认注入行为,因为在vue中,已经具备了这些功能。

看完这些,你或许对webapck.base.conf.js中的内容有了一些初步的了解。其实,看懂它还需要你了解webpack这个非常有用的打包工具。

之后,我们在来回看webpack.dev.conf.js这个文件

webpack.dev.conf.js

这个文件中,引用了webapck-merge这npm包,它可以将两个配置对象,进行合并。代码如下:

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

这样就合并了base中的webpack配置项。之后,我们可以来看一下dev环境中的新增了那些配置项,它们分别起到了什么作用?

  • 首先,在module的rules中增加了cssSourceMap的功能

  • 然后就是devtools,通过注释的英文翻译,可以知道cheap-module-eval-source-map使得开发更快。

  • 之后,就是devSever的一些配置项了。其中包块客户端报错级别、端口、host等等

  • 还有新增的plugins,我们可以来看一下实际新增的plugins(具体可以看webpack文档):

  • 定义process.env
    HotModuleReplacementPlugin: 模块热替换插件
    NameModulesPlugin: 显示模块加载相对路径插件
    NoEmitOnErrorsPlugin: 在编译出现错误时,使用 NoEmitOnErrorsPlugin 来跳过输出阶段。这样可以确保输出资源不会包含错误
    HtmlWebpackPlugin: 使用插件生成一个指定的模版。

后,还有一个函数,确保启动程序时,如果端口被占用时,会通过portfinder来发布新的端口,然后输出运行的host字符串。

webpack.prod.conf.js

这是打包到生产环境中,会被用到的文件。我们可以看到,它相对于之前的webapck.dev.conf.js文件少了一些插件,多了更多的插件。我们也可以和之前一样,通过它新增的一些东西,来知道它到底干了什么!(此处的新增是相对于webpack.dev.conf.js没有的内容)

  • 新增了output的配置,我们可以看到它在output中新增了一些属性,将js打包成不同的块chunk,然后使用hash尾缀进行命名

  • 添加一些插件:

  • UglifJsPlugin: 这个是用来丑化js代码的
    ExtractTextplugin: 这里新增了一些属性,在打包的css文件也增加了块和hash尾缀
    OptimizeCssplugin: 这里是来优化css文件的,主要就是压缩css代码
    HashedModuleIdsPlugin: 保证module的id值稳定
    optimize: 这里是webpack一系列优化的措施,具体可以逐一查看官方文档
    CopyWebPlugins: 自定义assets文件目录

  • 如果没有进行gzip压缩,调用CompressionWebpackPlugin插件进行压缩

这样,我们的webpack配置文件内容基本上就全部看完了。或许,会有点蒙,还是看官方文档来的实在。

最后,还需要分析一个build.js文件。

build.js

这个文件是在打包的时候,会被用到的。

首先,文件的开头请求了check-version.js中的函数,然后确定了一下node和npm的版本。相对于较低版本的node和npm,在打包过程中,会产生警告。之后,设置环境参数,设置成生产环境,之后就是一系列打包的流程。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

The above is the detailed content of Detailed explanation of the use of vue-cli. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

See all articles