Home >Web Front-end >JS Tutorial >Detailed explanation of the use of vue-cli
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
Install directory with webpack template
vue init webapck webpack-template
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')
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')
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, } }
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 }
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' } }
其中,主要就是根据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, { ... }
这样就合并了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!