这可能是vue-cli最全的解析了……(代码片段)

zhaowy zhaowy     2022-12-26     320

关键词:

题言:

相信很多vue新手,都像我一样,只是知道可以用vue-cli直接生成一个vue项目的架构,并不明白,他究竟是怎么运行的,现在我们一起来研究一下。。。

一、安装vue-cli,相信你既然会用到vue-cli,自然node环境是OK的,直接命令行下安装

npm install -g vue-cli

 

二、使用vue-cli创建vue项目

用法: vue init <template-name> <project-name>
1 template-name:
2     . webpack
3     . webpack-simple  // 一个简单webpack+vue-loader的模板,不包含其他功能。
4     . browserify     //  一个全面的Browserify+vueify 的模板,功能包括热加载,linting,单元检测。
5     . browserify-simple  // 一个简单Browserify+vueify的模板,不包含其他功能。
6     . pwa           // 基于webpack模板的vue-cli的PWA模板
7     . simple      //  一个最简单的单页应用模板  

 

常用的就是webpack了,模板之间的不同,自己体验
示例:

vue init webpack my-project

执行指令后,会让用户输入几个基本的选项,如图所示

技术分享图片

需要注意的是项目的名称不能大写,不然会报错。

  • Project name :项目名称 ,如果不需要更改直接回车就可以了。注意:这里不能使用大写。
  • Project description:项目描述,默认为A Vue.js project,直接回车,不用编写。
  • Author:作者,如果你有配置git,他会读取.ssh文件中的user。
  • Install vue-router? 是否安装vue的路由插件,Y代表安装,N无需安装,下面的命令也是一样的。
  • Use ESLint to lint your code? 是否用ESLint来限制你的代码错误和风格
  • setup unit tests with Karma + Mocha? 是否需要安装单元测试工具Karma+Mocha。
  • Setup e2e tests with Nightwatch?是否安装e2e来进行用户行为模拟测试。
  • Should we run npm install for you after the project has been created?(recommended)npm

    询问你使用npm安装还是yarn安装包依赖,我这里选择的是npm,yarn更快更好,使用yarn之前确保你的电脑已经安装yarn。

根据提示,待模板加载完成之后,执行下面两条命令

cd my-project

npm run dev   // dev代表下图框选的内容

 

技术分享图片

出现如图,就是编译成功了,英文稍微好点,就能读懂 
这时候,鼠标放到 http://localhost:8080 会提示用“Alt+点击”即可访问;
出现如图,就成功创建了项目;

技术分享图片

三、文件目录结构

本文主要分析开发(dev)和构建(build)两个过程涉及到的文件,故下面文件结构仅列出相应的内容。

|-- build                            // 项目构建(webpack)相关代码
|   |-- build.js                     // 生产环境构建代码
|   |-- check-version.js             // 检查node、npm等版本
|   |-- utils.js                     // 构建工具相关
|   |-- vue-loader.conf.js           // webpack loader配置
|   |-- webpack.base.conf.js         // webpack基础配置
|   |-- webpack.dev.conf.js          // webpack开发环境配置,构建开发本地服务器
|   |-- webpack.prod.conf.js         // webpack生产环境配置
|-- config                           // 项目开发环境配置
|   |-- dev.env.js                   // 开发环境变量
|   |-- index.js                     // 项目一些配置变量
|   |-- prod.env.js                  // 生产环境变量
|   |-- test.env.js                  // 测试脚本的配置
|-- src                              // 源码目录
|   |-- components                   // vue所有组件
|   |-- router                       // vue的路由管理
|   |-- App.vue                      // 页面入口文件
|   |-- main.js                      // 程序入口文件,加载各种公共组件
|-- static                           // 静态文件,比如一些图片,json数据等
|-- test                             // 测试文件
|   |-- e2e                          // e2e 测试
|   |-- unit                         // 单元测试
|-- .babelrc                         // ES6语法编译配置
|-- .editorconfig                    // 定义代码格式
|-- .eslintignore                    // eslint检测代码忽略的文件(夹)
|-- .eslintrc.js                     // 定义eslint的plugins,extends,rules
|-- .gitignore                       // git上传需要忽略的文件格式
|-- .postcsssrc                      // postcss配置文件
|-- README.md                        // 项目说明,markdown文档
|-- index.html                       // 访问的页面
|-- package.json                     // 项目基本信息,包依赖信息等

 

如图所示:

技术分享图片 
下边是具体文件的具体分析

1. package.json文件

package.json文件是项目的配置文件,定义了项目的基本信息以及项目的相关包依赖,npm运行命令等

技术分享图片

scripts 里定义的是一些比较长的命令,用node去执行一段命令,比如

npm run dev

其实就是执行


webpack-dev-server --inline --progress --config build/webpack.dev.conf.js

这句话的意思是利用 webpack-dev-server 读取 webpack.dev.conf.js 信息并启动一个本地服务器。

2. dependencies VS devDependencies

简单的来说

dependencies 是运行时依赖(生产环境)       npm install --save  **(package name)
devDependencies 是开发时的依赖(开发环境)  npm install --save-dev  **(package name)

 

3. 基础配置文件 webpack.base.conf.js

基础的 webpack 配置文件主要根据模式定义了入口出口,以及处理 vue, babel等的各种模块,是最为基础的部分。其他模式的配置文件以此为基础通过 webpack-merge 合并。

  1 ‘use strict‘
  2 const path = require(‘path‘)
  3 const utils = require(‘./utils‘)
  4 const config = require(‘../config‘)
  5 const vueLoaderConfig = require(‘./vue-loader.conf‘)
  6 
  7 // 获取绝对路径
  8 function resolve (dir) 
  9   return path.join(__dirname, ‘..‘, dir)
 10 
 11 <!-- 定义一下代码检测的规则 -->
 12 const createLintingRule = () => (
 13   test: /.(js|vue)$/,
 14   loader: ‘eslint-loader‘,
 15   enforce: ‘pre‘,
 16   include: [resolve(‘src‘), resolve(‘test‘)],
 17   options: 
 18     formatter: require(‘eslint-friendly-formatter‘),
 19     emitWarning: !config.dev.showEslintErrorsInOverlay
 20   
 21 )
 22 
 23 module.exports = 
 24   // 基础上下文
 25   context: path.resolve(__dirname, ‘../‘),
 26   // webpack的入口文件
 27   entry: 
 28     app: ‘./src/main.js‘
 29   ,
 30   // webpack的输出文件
 31   output: 
 32     path: config.build.assetsRoot,
 33     filename: ‘[name].js‘,
 34     publicPath: process.env.NODE_ENV === ‘production‘
 35       ? config.build.assetsPublicPath 
 36       : config.dev.assetsPublicPath  
 37   ,
 38   /**
 39    * 当webpack试图去加载模块的时候,它默认是查找以 .js 结尾的文件的,
 40    * 它并不知道 .vue 结尾的文件是什么鬼玩意儿,
 41    * 所以我们要在配置文件中告诉webpack,
 42    * 遇到 .vue 结尾的也要去加载,
 43    * 添加 resolve 配置项,如下:
 44    */
 45   resolve: 
 46     extensions: [‘.js‘, ‘.vue‘, ‘.json‘],
 47     alias:   // 创建别名
 48       ‘vue$‘: ‘vue/dist/vue.esm.js‘,
 49       ‘@‘: resolve(‘src‘),  // 如 ‘@/components/HelloWorld‘
 50     
 51   ,
 52   // 不同类型模块的处理规则 就是用不同的loader处理不同的文件
 53   module: 
 54     rules: [
 55       ...(config.dev.useEslint ? [createLintingRule()] : []),
 56       // 对所有.vue文件使用vue-loader进行编译
 57         test: /.vue$/,
 58         loader: ‘vue-loader‘,
 59         options: vueLoaderConfig
 60       ,
 61       // 对src和test文件夹下的.js文件使用babel-loader将es6+的代码转成es5
 62         test: /.js$/,
 63         loader: ‘babel-loader‘,
 64         include: [resolve(‘src‘), resolve(‘test‘), resolve(‘node_modules/webpack-dev-server/client‘)]
 65       ,
 66       // 对图片资源文件使用url-loader
 67         test: /.(png|jpe?g|gif|svg)(?.*)?$/,
 68         loader: ‘url-loader‘,
 69         options: 
 70           // 小于10K的图片转成base64编码的dataURL字符串写到代码中
 71           limit: 10000,
 72           // 其他的图片转移到静态资源文件夹
 73           name: utils.assetsPath(‘img/[name].[hash:7].[ext]‘)
 74         
 75       ,
 76       // 对多媒体资源文件使用url-loader
 77         test: /.(mp4|webm|ogg|mp3|wav|flac|aac)(?.*)?$/,
 78         loader: ‘url-loader‘,
 79         options: 
 80           // 小于10K的资源转成base64编码的dataURL字符串写到代码中
 81           limit: 10000,
 82           // 其他的资源转移到静态资源文件夹
 83           name: utils.assetsPath(‘media/[name].[hash:7].[ext]‘)
 84         
 85       ,
 86       // 对字体资源文件使用url-loader
 87         test: /.(woff2?|eot|ttf|otf)(?.*)?$/,
 88         loader: ‘url-loader‘,
 89         options: 
 90           limit: 10000,
 91           name: utils.assetsPath(‘fonts/[name].[hash:7].[ext]‘) // hash:7 代表 7 位数的 hash
 92         
 93       
 94     ]
 95   ,
 96   node: 
 97     // prevent webpack from injecting useless setImmediate polyfill because Vue
 98     // source contains it (although only uses it if it‘s native).
 99     setImmediate: false,
100     // prevent webpack from injecting mocks to Node native modules
101     // that does not make sense for the client
102     dgram: ‘empty‘,
103     fs: ‘empty‘,
104     net: ‘empty‘,
105     tls: ‘empty‘,
106     child_process: ‘empty‘
107   
108 

 

4. 开发环境配置文件 webpack.dev.conf.js

  1 ‘use strict‘
  2 const utils = require(‘./utils‘)
  3 const webpack = require(‘webpack‘)
  4 const config = require(‘../config‘)  // 基本配置的参数
  5 const merge = require(‘webpack-merge‘) // webpack-merge是一个可以合并数组和对象的插件
  6 const path = require(‘path‘)
  7 const baseWebpackConfig = require(‘./webpack.base.conf‘) // webpack基本配置文件(开发和生产环境公用部分)
  8 const CopyWebpackPlugin = require(‘copy-webpack-plugin‘)
  9 // html-webpack-plugin用于将webpack编译打包后的产品文件注入到html模板中
 10 // 即在index.html里面加上<link>和<script>标签引用webpack打包后的文件
 11 const HtmlWebpackPlugin = require(‘html-webpack-plugin‘)
 12 // friendly-errors-webpack-plugin用于更友好地输出webpack的警告、错误等信息
 13 const FriendlyErrorsPlugin = require(‘friendly-errors-webpack-plugin‘)
 14 const portfinder = require(‘portfinder‘) // 自动检索下一个可用端口
 15 
 16 const HOST = process.env.HOST
 17 const PORT = process.env.PORT && Number(process.env.PORT) ) // 读取系统环境变量的port
 18 
 19 // 合并baseWebpackConfig配置
 20 const devWebpackConfig = merge(baseWebpackConfig, 
 21   module: 
 22     // 对一些独立的css文件以及它的预处理文件做一个编译
 23     rules: utils.styleLoaders( sourceMap: config.dev.cssSourceMap, usePostCSS: true )
 24   ,
 25   // cheap-module-eval-source-map is faster for development
 26   devtool: config.dev.devtool,
 27 
 28   // these devServer options should be customized in /config/index.js
 29   devServer:   //  webpack-dev-server服务器配置
 30     clientLogLevel: ‘warning‘, // console 控制台显示的消息,可能的值有 none, error, warning 或者 info
 31     historyApiFallback: 
 32       rewrites: [
 33          from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, ‘index.html‘) ,
 34       ],
 35     ,
 36     hot: true, // 开启热模块加载
 37     contentBase: false, // since we use CopyWebpackPlugin.
 38     compress: true,
 39     host: HOST || config.dev.host, // process.env 优先
 40     port: PORT || config.dev.port, // process.env 优先
 41     open: config.dev.autoOpenBrowser, 
 42     overlay: config.dev.errorOverlay
 43       ?  warnings: false, errors: true 
 44       : false,
 45     publicPath: config.dev.assetsPublicPath,
 46     proxy: config.dev.proxyTable, // 代理设置
 47     quiet: true, // necessary for FriendlyErrorsPlugin
 48     watchOptions:  // 启用 Watch 模式。这意味着在初始构建之后,webpack 将继续监听任何已解析文件的更改
 49       poll: config.dev.poll, // 通过传递 true 开启 polling,或者指定毫秒为单位进行轮询。默认为false
 50     
 51   ,
 52   plugins: [
 53     new webpack.DefinePlugin(
 54       ‘process.env‘: require(‘../config/dev.env‘)
 55     ),
 56     /*模块热替换它允许在运行时更新各种模块,而无需进行完全刷新*/
 57     new webpack.HotModuleReplacementPlugin(),
 58     new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
 59     new webpack.NoEmitOnErrorsPlugin(),// 跳过编译时出错的代码并记录下来,主要作用是使编译后运行时的包不出错
 60     // https://github.com/ampedandwired/html-webpack-plugin
 61     new HtmlWebpackPlugin(
 62     // 指定编译后生成的html文件名
 63       filename: ‘index.html‘,
 64       // 需要处理的模板
 65       template: ‘index.html‘,
 66       // 打包过程中输出的js、css的路径添加到html文件中
 67       // css文件插入到head中
 68       // js文件插入到body中,可能的选项有 true, ‘head‘, ‘body‘, false
 69       inject: true
 70     ),
 71     // copy custom static assets
 72     new CopyWebpackPlugin([
 73       
 74         from: path.resolve(__dirname, ‘../static‘),
 75         to: config.dev.assetsSubDirectory,
 76         ignore: [‘.*‘]
 77       
 78     ])
 79   ]
 80 )
 81 
 82 module.exports = new Promise((resolve, reject) => 
 83   portfinder.basePort = process.env.PORT || config.dev.port // 获取当前设定的端口
 84   portfinder.getPort((err, port) => 
 85     if (err) 
 86       reject(err)
 87      else 
 88       // publish the new Port, necessary for e2e tests   发布新的端口,对于e2e测试
 89       process.env.PORT = port
 90       // add port to devServer config
 91       devWebpackConfig.devServer.port = port
 92 
 93       // Add FriendlyErrorsPlugin
 94       devWebpackConfig.plugins.push(new FriendlyErrorsPlugin(
 95         compilationSuccessInfo: 
 96           messages: [`Your application is running here: http://$devWebpackConfig.devServer.host:$port`],
 97         ,
 98         onErrors: config.dev.notifyOnErrors
 99         ? utils.createNotifierCallback()
100         : undefined
101       ))
102 
103       resolve(devWebpackConfig)
104     
105   )
106 )

 

5. 生产模式配置文件 webpack.prod.conf.js

  1 ‘use strict‘
  2 const path = require(‘path‘)
  3 const utils = require(‘./utils‘)
  4 const webpack = require(‘webpack‘)
  5 const config = require(‘../config‘)
  6 const merge = require(‘webpack-merge‘)
  7 const baseWebpackConfig = require(‘./webpack.base.conf‘)
  8 // copy-webpack-plugin,用于将static中的静态文件复制到产品文件夹dist
  9 const CopyWebpackPlugin = require(‘copy-webpack-plugin‘)
 10 const HtmlWebpackPlugin = require(‘html-webpack-plugin‘)
 11 const ExtractTextPlugin = require(‘extract-text-webpack-plugin‘)
 12 // optimize-css-assets-webpack-plugin,用于优化和最小化css资源
 13 const OptimizeCSSPlugin = require(‘optimize-css-assets-webpack-plugin‘)
 14 // uglifyJs 混淆js插件
 15 const UglifyJsPlugin = require(‘uglifyjs-webpack-plugin‘)
 16 
 17 const env = process.env.NODE_ENV === ‘testing‘
 18   ? require(‘../config/test.env‘)
 19   : require(‘../config/prod.env‘)
 20 
 21 const webpackConfig = merge(baseWebpackConfig, 
 22   module: 
 23     // 样式文件的处理规则,对css/sass/scss等不同内容使用相应的styleLoaders
 24     // 由utils配置出各种类型的预处理语言所需要使用的loader,例如sass需要使用sass-loader
 25     rules: utils.styleLoaders(
 26       sourceMap: config.build.productionSourceMap,
 27       extract: true,
 28       usePostCSS: true
 29     )
 30   ,
 31   devtool: config.build.productionSourceMap ? config.build.devtool : false,
 32   // webpack输出路径和命名规则
 33   output: 
 34     path: config.build.assetsRoot,
 35     filename: utils.assetsPath(‘js/[name].[chunkhash].js‘),
 36     chunkFilename: utils.assetsPath(‘js/[id].[chunkhash].js‘)
 37   ,
 38   plugins: [
 39     // http://vuejs.github.io/vue-loader/en/workflow/production.html
 40     new webpack.DefinePlugin(
 41       ‘process.env‘: env
 42     ),
 43     // 丑化压缩JS代码
 44     new UglifyJsPlugin(
 45       uglifyOptions: 
 46         compress: 
 47           warnings: false
 48         
 49       ,
 50       sourceMap: config.build.productionSourceMap,
 51       parallel: true
 52     ),
 53     // extract css into its own file
 54     // 将css提取到单独的文件
 55     new ExtractTextPlugin(
 56       filename: utils.assetsPath(‘css/[name].[contenthash].css‘),
 57       // Setting the following option to `false` will not extract CSS from codesplit chunks.
 58       // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
 59       // It‘s currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it‘s `false`, 
 60       // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
 61       allChunks: true,
 62     ),
 63     // Compress extracted CSS. We are using this plugin so that possible
 64     // duplicated CSS from different components can be deduped.
 65     // 优化、最小化css代码,如果只简单使用extract-text-plugin可能会造成css重复
 66     // 具体原因可以看npm上面optimize-css-assets-webpack-plugin的介绍
 67     new OptimizeCSSPlugin(
 68       cssProcessorOptions: config.build.productionSourceMap
 69         ?  safe: true, map:  inline: false  
 70         :  safe: true 
 71     ),
 72     // generate dist index.html with correct asset hash for caching.
 73     // you can customize output by editing /index.html
 74     // see https://github.com/ampedandwired/html-webpack-plugin
 75     // 将产品文件的引用注入到index.html
 76     new HtmlWebpackPlugin(
 77       filename: process.env.NODE_ENV === ‘testing‘
 78         ? ‘index.html‘
 79         : config.build.index,
 80       template: ‘index.html‘,
 81       inject: true,
 82       minify: 
 83         // 删除index.html中的注释
 84         removeComments: true,
 85         // 删除index.html中的空格
 86         collapseWhitespace: true,
 87         // 删除各种html标签属性值的双引号
 88         removeAttributeQuotes: true
 89         // more options:
 90         // https://github.com/kangax/html-minifier#options-quick-reference
 91       ,
 92       // necessary to consistently work with multiple chunks via CommonsChunkPlugin
 93       // 注入依赖的时候按照依赖先后顺序进行注入,比如,需要先注入vendor.js,再注入app.js
 94       chunksSortMode: ‘dependency‘
 95     ),
 96     // keep module.id stable when vendor modules does not change
 97     new webpack.HashedModuleIdsPlugin(),
 98     // enable scope hoisting
 99     new webpack.optimize.ModuleConcatenationPlugin(),
100     // split vendor js into its own file
101     // 将所有从node_modules中引入的js提取到vendor.js,即抽取库文件
102     new webpack.optimize.CommonsChunkPlugin(
103       name: ‘vendor‘,
104       minChunks (module) 
105         // any required modules inside node_modules are extracted to vendor
106         return (
107           module.resource &&
108           /.js$/.test(module.resource) &&
109           module.resource.indexOf(
110             path.join(__dirname, ‘../node_modules‘)
111           ) === 0
112         )
113       
114     ),
115     // extract webpack runtime and module manifest to its own file in order to
116     // prevent vendor hash from being updated whenever app bundle is updated
117     // 从vendor中提取出manifest,原因如上
118     new webpack.optimize.CommonsChunkPlugin(
119       name: ‘manifest‘,
120       minChunks: Infinity
121     ),
122     // This instance extracts shared chunks from code splitted chunks and bundles them
123     // in a separate chunk, similar to the vendor chunk
124     // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
125     new webpack.optimize.CommonsChunkPlugin(
126       name: ‘app‘,
127       async: ‘vendor-async‘,
128       children: true,
129       minChunks: 3
130     ),
131 
132     // copy custom static assets
133     // 将static文件夹里面的静态资源复制到dist/static
134     new CopyWebpackPlugin([
135       
136         from: path.resolve(__dirname, ‘../static‘),
137         to: config.build.assetsSubDirectory,
138         ignore: [‘.*‘]
139       
140     ])
141   ]
142 )
143 
144 // 如果开启了产品gzip压缩,则利用插件将构建后的产品文件进行压缩
145 if (config.build.productionGzip) 
146   // 一个用于压缩的webpack插件
147   const CompressionWebpackPlugin = require(‘compression-webpack-plugin‘)
148 
149   webpackConfig.plugins.push(
150     new CompressionWebpackPlugin(
151       asset: ‘[path].gz[query]‘,
152       // 压缩算法
153       algorithm: ‘gzip‘,
154       test: new RegExp(
155         ‘\.(‘ +
156         config.build.productionGzipExtensions.join(‘|‘) +
157         ‘)$‘
158       ),
159       threshold: 10240,
160       minRatio: 0.8
161     )
162   )
163 
164 
165 // 如果启动了report,则通过插件给出webpack构建打包后的产品文件分析报告
166 if (config.build.bundleAnalyzerReport) 
167   const BundleAnalyzerPlugin = require(‘webpack-bundle-analyzer‘).BundleAnalyzerPlugin
168   webpackConfig.plugins.push(new BundleAnalyzerPlugin())
169 
170 
171 module.exports = webpackConfig

 

6. build.js 编译入口

 1 ‘use strict‘
 2 require(‘./check-versions‘)()
 3 
 4 process.env.NODE_ENV = ‘production‘
 5 // ora,一个可以在终端显示spinner的插件
 6 const ora = require(‘ora‘)
 7 // rm,用于删除文件或文件夹的插件
 8 const rm = require(‘rimraf‘)
 9 const path = require(‘path‘)
10 // chalk,用于在控制台输出带颜色字体的插件
11 const chalk = require(‘chalk‘)
12 const webpack = require(‘webpack‘)
13 const config = require(‘../config‘)
14 const webpackConfig = require(‘./webpack.prod.conf‘)
15 
16 const spinner = ora(‘building for production...‘)
17 spinner.start() // 开启loading动画
18 
19 // 首先将整个dist文件夹以及里面的内容删除,以免遗留旧的没用的文件
20 // 删除完成后才开始webpack构建打包
21 rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => 
22   if (err) throw err
23   // 执行webpack构建打包,完成之后在终端输出构建完成的相关信息或者输出报错信息并退出程序
24   webpack(webpackConfig, (err, stats) => 
25     spinner.stop()
26     if (err) throw err
27     process.stdout.write(stats.toString(
28       colors: true,
29       modules: false,
30       children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
31       chunks: false,
32       chunkModules: false
33     ) + ‘

‘)
34 
35     if (stats.hasErrors()) 
36       console.log(chalk.red(‘  Build failed with errors.
‘))
37       process.exit(1)
38     
39 
40     console.log(chalk.cyan(‘  Build complete.
‘))
41     console.log(chalk.yellow(
42       ‘  Tip: built files are meant to be served over an HTTP server.
‘ +
43       ‘  Opening index.html over file:// won‘t work.
‘
44     ))
45   )
46 )

 

7. 实用代码段 utils.js

  1 ‘use strict‘
  2 const path = require(‘path‘)
  3 const config = require(‘../config‘)
  4 // extract-text-webpack-plugin可以提取bundle中的特定文本,将提取后的文本单独存放到另外的文件
  5 // 这里用来提取css样式
  6 const ExtractTextPlugin = require(‘extract-text-webpack-plugin‘)
  7 const packageConfig = require(‘../package.json‘)
  8 
  9 // 资源文件的存放路径
 10 exports.assetsPath = function (_path) 
 11   const assetsSubDirectory = process.env.NODE_ENV === ‘production‘
 12     ? config.build.assetsSubDirectory
 13     : config.dev.assetsSubDirectory
 14 
 15   return path.posix.join(assetsSubDirectory, _path)
 16 
 17 
 18 // 生成css、sass、scss等各种用来编写样式的语言所对应的loader配置
 19 exports.cssLoaders = function (options) 
 20   options = options || 
 21   // css-loader配置
 22   const cssLoader = 
 23     loader: ‘css-loader‘,
 24     options: 
 25       // 是否使用source-map
 26       sourceMap: options.sourceMap
 27     
 28   
 29 
 30   const postcssLoader = 
 31     loader: ‘postcss-loader‘,
 32     options: 
 33       sourceMap: options.sourceMap
 34     
 35   
 36 
 37   // generate loader string to be used with extract text plugin
 38   // 生成各种loader配置,并且配置了extract-text-pulgin
 39   function generateLoaders (loader, loaderOptions) 
 40     const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
 41     // 例如generateLoaders(‘less‘),这里就会push一个less-loader
 42     // less-loader先将less编译成css,然后再由css-loader去处理css
 43     // 其他sass、scss等语言也是一样的过程
 44     if (loader) 
 45       loaders.push(
 46         loader: loader + ‘-loader‘,
 47         options: Object.assign(, loaderOptions, 
 48           sourceMap: options.sourceMap
 49         )
 50       )
 51     
 52 
 53     // Extract CSS when that option is specified
 54     // (which is the case during production build)
 55     if (options.extract) 
 56       // 配置extract-text-plugin提取样式
 57       return ExtractTextPlugin.extract(
 58         use: loaders,
 59         fallback: ‘vue-style-loader‘
 60       )
 61      else 
 62        // 无需提取样式则简单使用vue-style-loader配合各种样式loader去处理<style>里面的样式
 63       return [‘vue-style-loader‘].concat(loaders)
 64     
 65   
 66 
 67   // https://vue-loader.vuejs.org/en/configurations/extract-css.html
 68   // 得到各种不同处理样式的语言所对应的loader
 69   return 
 70     css: generateLoaders(),
 71     postcss: generateLoaders(),
 72     less: generateLoaders(‘less‘),
 73     sass: generateLoaders(‘sass‘,  indentedSyntax: true ),
 74     scss: generateLoaders(‘sass‘),
 75     stylus: generateLoaders(‘stylus‘),
 76     styl: generateLoaders(‘stylus‘)
 77   
 78 
 79 
 80 // Generate loaders for standalone style files (outside of .vue)
 81 // 生成处理单独的.css、.sass、.scss等样式文件的规则
 82 exports.styleLoaders = function (options) 
 83   const output = []
 84   const loaders = exports.cssLoaders(options)
 85 
 86   for (const extension in loaders) 
 87     const loader = loaders[extension]
 88     output.push(
 89       test: new RegExp(‘\.‘ + extension + ‘$‘),
 90       use: loader
 91     )
 92   
 93 
 94   return output
 95 
 96 
 97 exports.createNotifierCallback = () => 
 98   const notifier = require(‘node-notifier‘)
 99 
100   return (severity, errors) => 
101     if (severity !== ‘error‘) return
102 
103     const error = errors[0]
104     const filename = error.file && error.file.split(‘!‘).pop()
105 
106     notifier.notify(
107       title: packageConfig.name,
108       message: severity + ‘: ‘ + error.name,
109       subtitle: filename || ‘‘,
110       icon: path.join(__dirname, ‘logo.png‘)
111     )
112   
113 

 

8. babel配置文件.babelrc

 1  //设定转码规则
 2   "presets": [
 3     ["env", 
 4       "modules": false,
 5       //对BABEL_ENV或者NODE_ENV指定的不同的环境变量,进行不同的编译操作
 6       "targets": 
 7         "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
 8       
 9     ],
10     "stage-2"
11   ],
12   //转码用的插件
13   "plugins": ["transform-vue-jsx", "transform-runtime"]
14 

9 .编码规范.editorconfig (自定义)

1 root = true
2 
3 [*]    // 对所有文件应用下面的规则
4 charset = utf-8                    // 编码规则用utf-8
5 indent_style = space               // 缩进用空格
6 indent_size = 2                    // 缩进数量为2个空格
7 end_of_line = lf                   // 换行符格式
8 insert_final_newline = true        // 是否在文件的最后插入一个空行
9 trim_trailing_whitespace = true    // 是否删除行尾的空格

10 .src/app.vue文件解读

 1 <template>
 2   <div id="app">
 3     <img src="./assets/logo.png">
 4     <router-view></router-view>
 5   </div>
 6 </template>
 7 
 8 <script>
 9 export default 
10   name: ‘app‘
11 
12 </script>
13 
14 <style>
15 #app 
16   font-family: ‘Avenir‘, Helvetica, Arial, sans-serif;
17   -webkit-font-smoothing: antialiased;
18   -moz-osx-font-smoothing: grayscale;
19   text-align: center;
20   color: #2c3e50;
21   margin-top: 60px;
22 
23 </style>
<template></template> 标签包裹的内容:这是模板的HTMLDom结构 
<script></script>     标签包括的js内容:你可以在这里写一些页面的js的逻辑代码。 
<style></style>       标签包裹的css内容:页面需要的CSS样式。

11. src/router/index.js 路由文件

 1 import Vue from ‘vue‘
 2 import Router from ‘vue-router‘
 3 import Hello from ‘@/components/Hello‘
 4 
 5 Vue.use(Router)
 6 
 7 export default new Router(
 8   routes: [//配置路由
 9     
10       path: ‘/‘,        //访问路径
11       name: ‘Hello‘,    //路由名称
12       component: Hello  //路由需要的组件(驼峰式命名)
13     
14   ]

 

12. eslint的相关配置(按照AirBnb的规则检测);

 







vue-cli解析(代码片段)

前言这段时间,算是空出手来写几篇文章了。由于很久都没有时间整理现在所用的东西了,所以,接下来会慢慢整理出一些文档来记录前段时间的工作和生活。这篇文章的主题是vue-cli的理解。或许,很多人在开发vue的时候,我... 查看详情

这可能是把nginx讲得最全面的一篇文章了,建议收藏备用(代码片段)

点击上方关注“终端研发部”设为“星标”,和你一起掌握更多数据库知识前言Nginx概述Nginx特点Nginx作用Nginx安装Nginx常用命令Nginx核心配置配置文件结构配置文件main段核心参数配置文件events段核心参数server_name指令rootaliasloca... 查看详情

2.3w字,这可能是把nginx讲得最全面的一篇文章了,建议收藏备用(代码片段)

前言Nginx概述Nginx特点Nginx作用Nginx安装Nginx常用命令Nginx核心配置配置文件结构配置文件main段核心参数配置文件events段核心参数server_name指令rootaliaslocationrewriteif指令autoindex变量Nginx应用核心概念正向代理反向代理动静分离负载均... 查看详情

navigationmove_base最最全解析(按执行逻辑梳理)(代码片段)

零、前言此前写了一篇对move_base的解析,号称全网最全,因为把整个包都加了注释hhh。但是那篇文章由于是以源代码+注释的形式呈现,存在诸多问题,比如:没有按照逻辑顺序解析(而阅读代码的正确步骤是按照程序执行顺序... 查看详情

这可能是最牛逼的java权限框架了。。(代码片段)

今天给大家推荐的这个开源项目超级棒,可能是史上功能最全的Java权限认证框架!这个开源项目就是:sa-token。Sa-Token是什么?sa-token是一个轻量级Java权限认证框架,主要解决:登录认证、权限认证、Session... 查看详情

这可能是最全的总结了,详解20个pandas读与写函数(代码片段)

大家好,今天来为大家介绍几个Pandas读取数据以及保存数据的方法,毕竟我们很多时候需要读取各种形式的数据,以及将我们需要将所做的统计分析保存成特定的格式。注:应很多朋友的要求,文末创建了技... 查看详情

wpf这可能是全网最全的拖拽实现方法的总结

原文:【WPF】这可能是全网最全的拖拽实现方法的总结前文本文只对笔者学习掌握的一般的拖动问题的实现方法进行整理和讨论,包括窗口、控件等内容的拖动。希望本文能对一些寻找此问题的解决方法的人和一些刚入门的人一... 查看详情

最全面解析spring框架ioc容器和aop面向切面(代码片段)

...的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由 查看详情

别找了,这可能是全网最全的鸿蒙(harmonyos)刷机指南!

本文的目的是将鸿蒙2.0刷到润和Hi3861、Hi3516和Hi3518开发板上。目前网上已经有很多关于刷鸿蒙2.0的文章,我整理了一下,并结合自己的经验,在本文中阐述了从配置环境,到编译鸿蒙源代码,再到刷机的全过... 查看详情

wpf这可能是全网最全的拖拽实现方法的总结

前文本文只对笔者学习掌握的一般的拖动问题的实现方法进行整理和讨论,包括窗口、控件等内容的拖动。希望本文能对一些寻找此问题的解决方法的人和一些刚入门的人一些帮助。笔者为WPF初学者,能得到各位的批评指正也是... 查看详情

❤️十大排序算法详解❤️——可能是你看过最全的,完整版代码(代码片段)

文章目录前言交集排序冒泡简单快速排序插入排序直接插入排序希尔排序选择排序简单选择排序堆排序归并排序二路多路非比较类计数排序桶排序基数排序最后前言兄弟们,应上篇数据结构的各位要求,今天我开始工作... 查看详情

这应该是你见过的最全前端下载总结(代码片段)

...件下载下来。暂时还没有接触过其他类型的,所以本项目可能有一定的局限性,只是给大家提供一种思路或者方案,有其他想法欢迎评论~纯前端下载形式顾名思义 查看详情

史上最全正则(代码片段)

...用正则也非常爽,可是到了OC这却把我虐了一把,可能是对OC掌握的不够。这里就罗列了 查看详情

最全面解析spring框架ioc容器和aop面向切面(代码片段)

...的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。简单来说,Spr... 查看详情

可能是史上最全vue前端代码风格指南(代码片段)

作者:卡喵妹https://juejin.cn/post/6987349513836953607一、命名规范市面上常用的命名规范:camelCase(小驼峰式命名法——首字母小写)PascalCase(大驼峰式命名法——首字母大写)kebab-case(短横线连接式)... 查看详情

查看vue-cli的两个命令(代码片段)

前言有的时候想要查看自己的vue-cli的版本,但是不知道怎么查看,这个时候就可以使用这两个命令了注意:这两个命令都是在装了全局的vue-cli的基础上,并且通过cmd窗口操作的方式1:打开命令窗口输入:... 查看详情

可能是全网最全的http面试答案(代码片段)

...GET无害:刷新、后退等浏览器操作GET请求是无害的,POST可能重复提交表单特性不同:GET是安全(这里的安全是指只读特性,就是使用这个方法不会 查看详情

vue-cli中自定义路径别名assets和static文件夹的区别(代码片段)

...分别是src/assets文件夹和static文件夹,这两者的区别很多人可能不太清楚。assets目录中的文件会被webpack处理解析为模块依赖,只支持相对路径形式。例如,在 <imgsr 查看详情