当前位置:   article > 正文

这可能是vue-cli最全的解析了……

这可能是vue-cli最全的解析了
题言:

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

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

  1. npm install -g vue-cli
  2. 复制代码

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

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

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

  1. vue init webpack my-project
  2. 复制代码

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

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

  • 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。

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

  1. cd my-project
  2. npm run dev // dev代表下图框选的内容
  3. 复制代码

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

三、文件目录结构

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

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

如图所示:

下边是具体文件的具体分析

1. package.json文件

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

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

  1. npm run dev
  2. 复制代码

其实就是执行

  1. webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
  2. 复制代码

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

2. dependencies VS devDependencies

简单的来说

  1. dependencies 是运行时依赖(生产环境) npm install --save **(package name)
  2. devDependencies 是开发时的依赖(开发环境) npm install --save-dev **(package name)
  3. 复制代码

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

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

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

6. build.js 编译入口

  1. 'use strict'
  2. require('./check-versions')()
  3. process.env.NODE_ENV = 'production'
  4. // ora,一个可以在终端显示spinner的插件
  5. const ora = require('ora')
  6. // rm,用于删除文件或文件夹的插件
  7. const rm = require('rimraf')
  8. const path = require('path')
  9. // chalk,用于在控制台输出带颜色字体的插件
  10. const chalk = require('chalk')
  11. const webpack = require('webpack')
  12. const config = require('../config')
  13. const webpackConfig = require('./webpack.prod.conf')
  14. const spinner = ora('building for production...')
  15. spinner.start() // 开启loading动画
  16. // 首先将整个dist文件夹以及里面的内容删除,以免遗留旧的没用的文件
  17. // 删除完成后才开始webpack构建打包
  18. rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  19. if (err) throw err
  20. // 执行webpack构建打包,完成之后在终端输出构建完成的相关信息或者输出报错信息并退出程序
  21. webpack(webpackConfig, (err, stats) => {
  22. spinner.stop()
  23. if (err) throw err
  24. process.stdout.write(stats.toString({
  25. colors: true,
  26. modules: false,
  27. children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
  28. chunks: false,
  29. chunkModules: false
  30. }) + '\n\n')
  31. if (stats.hasErrors()) {
  32. console.log(chalk.red(' Build failed with errors.\n'))
  33. process.exit(1)
  34. }
  35. console.log(chalk.cyan(' Build complete.\n'))
  36. console.log(chalk.yellow(
  37. ' Tip: built files are meant to be served over an HTTP server.\n' +
  38. ' Opening index.html over file:// won\'t work.\n'
  39. ))
  40. })
  41. })
  42. 复制代码

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

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. }
  15. 复制代码

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

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

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. <script>
  8. export default {
  9. name: 'app'
  10. }
  11. </script>
  12. <style>
  13. #app {
  14. font-family: 'Avenir', Helvetica, Arial, sans-serif;
  15. -webkit-font-smoothing: antialiased;
  16. -moz-osx-font-smoothing: grayscale;
  17. text-align: center;
  18. color: #2c3e50;
  19. margin-top: 60px;
  20. }
  21. </style>
  22. 复制代码
  1. <template></template> 标签包裹的内容:这是模板的HTMLDom结构
  2. <script></script> 标签包括的js内容:你可以在这里写一些页面的js的逻辑代码。
  3. <style></style> 标签包裹的css内容:页面需要的CSS样式。
  4. 复制代码

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

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

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

网上看了张挺有意思的图:

vue-cli项目图:

写在最后: 关于配置文件的注释都写在代码里了,可以单独Copy出来看,有什么好的想法或者建议,可以加我微信,欢迎交流……

原文链接:vue-cli详细解析

参考文章:

  1. vue-cli
  2. webpack-dev-server
  3. vue-cli项目结构详解
  4. vue-cli的webpack模板项目配置

转载于:https://juejin.im/post/5b2872516fb9a00e8626e34f

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/505827?site
推荐阅读
相关标签
  

闽ICP备14008679号