资讯专栏INFORMATION COLUMN

Vue-cli 命令行工具分析

LoftySoul / 3273人阅读

摘要:文章来源命令行工具分析命令行工具分析提供一个官方命令行工具,可用于快速搭建大型单页应用。其他模式的配置文件以此为基础通过合并。

文章来源:Vue-cli 命令行工具分析

Vue-cli 命令行工具分析

Vue.js 提供一个官方命令行工具,可用于快速搭建大型单页应用。vue-webpack-boilerplate,官方定义为:

</>复制代码

  1. full-featured Webpack setup with hot-reload, lint-on-save, unit testing & css extraction.

目录结构:

</>复制代码

  1. ├── README.md
  2. ├── build
  3. │ ├── build.js
  4. │ ├── utils.js
  5. │ ├── vue-loader.conf.js
  6. │ ├── webpack.base.conf.js
  7. │ ├── webpack.dev.conf.js
  8. │ └── webpack.prod.conf.js
  9. ├── config
  10. │ ├── dev.env.js
  11. │ ├── index.js
  12. │ └── prod.env.js
  13. ├── index.html
  14. ├── package.json
  15. ├── src
  16. │ ├── App.vue
  17. │ ├── assets
  18. │ │ └── logo.png
  19. │ ├── components
  20. │ │ └── Hello.vue
  21. │ └── main.js
  22. └── static
config 环境配置

config 配置文件用来配置 devServer 的相关设定,通过配置 NODE_ENV 来确定使用何种模式(开发、生产、测试或其他)

</>复制代码

  1. config
  2. |- index.js #配置文件
  3. |- dev.env.js #开发模式
  4. |- prod.env.js #生产模式
index.js

</>复制代码

  1. "use strict"
  2. const path = require("path");
  3. module.exports = {
  4. dev: {
  5. // 路径
  6. assetsSubDirectory: "static", // path:用来存放打包后文件的输出目录
  7. assetsPublicPath: "/", // publicPath:指定资源文件引用的目录
  8. proxyTable: {}, // 代理示例: proxy: [{context: ["/auth", "/api"],target: "http://localhost:3000",}]
  9. // 开发服务器变量设置
  10. host: "localhost",
  11. port: 8080,
  12. autoOpenBrowser: true, // 自动打开浏览器devServer.open
  13. errorOverlay: true, // 浏览器错误提示 devServer.overlay
  14. notifyOnErrors: true, // 配合 friendly-errors-webpack-plugin
  15. poll: true, // 使用文件系统(file system)获取文件改动的通知devServer.watchOptions
  16. // source map
  17. cssSourceMap: false, // develop 下不生成 sourceMap
  18. devtool: "eval-source-map" // 增强调试 可能的推荐值:eval, eval-source-map(推荐), cheap-eval-source-map, cheap-module-eval-source-map 详细:https://doc.webpack-china.org/configuration/devtool
  19. },
  20. build: {
  21. // index模板文件
  22. index: path.resolve(__dirname, "../dist/index.html"),
  23. // 路径
  24. assetsRoot: path.resolve(__dirname, "../dist"),
  25. assetsSubDirectory: "static",
  26. assetsPublicPath: "/",
  27. // bundleAnalyzerReport
  28. bundleAnalyzerReport: process.env.npm_config_report,
  29. // Gzip
  30. productionGzip: false, // 默认 false
  31. productionGzipExtensions: ["js", "css"],
  32. // source map
  33. productionSourceMap: true, // production 下是生成 sourceMap
  34. devtool: "#source-map" // devtool: "source-map" ?
  35. }
  36. }
dev.env.js

</>复制代码

  1. "use strict"
  2. const merge = require("webpack-merge");
  3. const prodEnv = require("./prod.env");
  4. module.exports = merge(prodEnv, {
  5. NODE_ENV: ""development""
  6. });
prod.env.js

</>复制代码

  1. "use strict"
  2. module.exports = {
  3. NODE_ENV: ""production""
  4. };
build Webpack配置

</>复制代码

  1. build
  2. |- utils.js #代码段
  3. |- webpack.base.conf.js #基础配置文件
  4. |- webpack.dev.conf.js #开发模式配置文件
  5. |- webpack.prod.conf.js #生产模式配置文件
  6. |- build.js #编译入口
实用代码段 utils.js

</>复制代码

  1. const config = require("../config")
  2. const path = require("path")
  3. exports.assetsPath = function (_path) {
  4. const assetsSubDirectory = process.env.NODE_ENV === "production"
  5. ? config.build.assetsSubDirectory // "static"
  6. : config.dev.assetsSubDirectory
  7. return path.posix.join(assetsSubDirectory, _path) // posix方法修正路径
  8. }
  9. exports.cssLoaders = function (options) { // 示例: ({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  10. options = options || {};
  11. // cssLoader
  12. const cssLoader = {
  13. loader: "css-loader",
  14. options: { sourceMap: options.sourceMap }
  15. }
  16. // postcssLoader
  17. var postcssLoader = {
  18. loader: "postcss-loader",
  19. options: { sourceMap: options.sourceMap }
  20. }
  21. // 生成 loader
  22. function generateLoaders (loader, loaderOptions) {
  23. const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] // 设置默认loader
  24. if (loader) {
  25. loaders.push({
  26. loader: loader + "-loader",
  27. options: Object.assign({}, loaderOptions, { // 生成 options 对象
  28. sourceMap: options.sourceMap
  29. })
  30. })
  31. }
  32. // 生产模式中提取css
  33. if (options.extract) { // 如果 options 中的 extract 为 true 配合生产模式
  34. return ExtractTextPlugin.extract({
  35. use: loaders,
  36. fallback: "vue-style-loader" // 默认使用 vue-style-loader
  37. })
  38. } else {
  39. return ["vue-style-loader"].concat(loaders)
  40. }
  41. }
  42. return { // 返回各种 loaders 对象
  43. css: generateLoaders(),
  44. postcss: generateLoaders(),
  45. less: generateLoaders("less"),
  46. // 示例:[
  47. // { loader: "css-loader", options: { sourceMap: true/false } },
  48. // { loader: "postcss-loader", options: { sourceMap: true/false } },
  49. // { loader: "less-loader", options: { sourceMap: true/false } },
  50. // ]
  51. sass: generateLoaders("sass", { indentedSyntax: true }),
  52. scss: generateLoaders("sass"),
  53. stylus: generateLoaders("stylus"),
  54. styl: generateLoaders("stylus")
  55. }
  56. }
  57. exports.styleLoaders = function (options) {
  58. const output = [];
  59. const loaders = exports.cssLoaders(options);
  60. for (const extension in loaders) {
  61. const loader = loaders[extension]
  62. output.push({
  63. test: new RegExp("." + extension + "$"),
  64. use: loader
  65. })
  66. // 示例:
  67. // {
  68. // test: new RegExp(.less$),
  69. // use: {
  70. // loader: "less-loader", options: { sourceMap: true/false }
  71. // }
  72. // }
  73. }
  74. return output
  75. }
  76. exports.createNotifierCallback = function () { // 配合 friendly-errors-webpack-plugin
  77. // 基本用法:notifier.notify("message");
  78. const notifier = require("node-notifier"); // 发送跨平台通知系统
  79. return (severity, errors) => {
  80. // 当前设定是只有出现 error 错误时触发 notifier 发送通知
  81. if (severity !== "error") { return } // 严重程度可以是 "error""warning"
  82. const error = errors[0]
  83. const filename = error.file && error.file.split("!").pop();
  84. notifier.notify({
  85. title: pkg.name,
  86. message: severity + ": " + error.name,
  87. subtitle: filename || ""
  88. // icon: path.join(__dirname, "logo.png") // 通知图标
  89. })
  90. }
  91. }
基础配置文件 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. function resolve(dir) {
  6. return path.join(__dirname, "..", dir);
  7. }
  8. module.exports = {
  9. context: path.resolve(__dirname, "../"), // 基础目录
  10. entry: {
  11. app: "./src/main.js"
  12. },
  13. output: {
  14. path: config.build.assetsRoot, // 默认"../dist"
  15. filename: "[name].js",
  16. publicPath: process.env.NODE_ENV === "production"
  17. ? config.build.assetsPublicPath // 生产模式publicpath
  18. : config.dev.assetsPublicPath // 开发模式publicpath
  19. },
  20. resolve: { // 解析确定的拓展名,方便模块导入
  21. extensions: [".js", ".vue", ".json"],
  22. alias: { // 创建别名
  23. "vue$": "vue/dist/vue.esm.js",
  24. "@": resolve("src") //"@/components/HelloWorld"
  25. }
  26. },
  27. module: {
  28. rules: [{
  29. test: /.vue$/, // vue 要在babel之前
  30. loader: "vue-loader",
  31. options: vueLoaderConfig //可选项: vue-loader 选项配置
  32. },{
  33. test: /.js$/, // babel
  34. loader: "babel-loader",
  35. include: [resolve("src")]
  36. },{ // url-loader 文件大小低于指定的限制时,可返回 DataURL,即base64
  37. test: /.(png|jpe?g|gif|svg)(?.*)?$/, // url-loader 图片
  38. loader: "url-loader",
  39. options: { // 兼容性问题需要将query换成options
  40. limit: 10000, // 默认无限制
  41. name: utils.assetsPath("img/[name].[hash:7].[ext]") // hash:7 代表 7 位数的 hash
  42. }
  43. },{
  44. test: /.(mp4|webm|ogg|mp3|wav|flac|aac)(?.*)?$/, // url-loader 音视频
  45. loader: "url-loader",
  46. options: {
  47. limit: 10000,
  48. name: utils.assetsPath("media/[name].[hash:7].[ext]")
  49. }
  50. },{
  51. test: /.(woff2?|eot|ttf|otf)(?.*)?$/, // url-loader 字体
  52. loader: "url-loader",
  53. options: {
  54. limit: 10000,
  55. name: utils.assetsPath("fonts/[name].[hash:7].[ext]")
  56. }
  57. }
  58. ]
  59. },
  60. node: { // 是否 polyfill 或 mock
  61. setImmediate: false,
  62. dgram: "empty",
  63. fs: "empty",
  64. net: "empty",
  65. tls: "empty",
  66. child_process: "empty"
  67. }
  68. }
开发模式配置文件 webpack.dev.conf.js

开发模式的配置文件主要引用了 config 对于 devServer 的设定,对 css 文件的处理,使用 DefinePlugin 判断是否生产环境,以及其他一些插件。

</>复制代码

  1. "use strict"
  2. const webpack = require("webpack");
  3. const config = require("../config");
  4. const merge = require("webpack-merge");
  5. const baseWebpackConfig = require("./webpack.base.conf");
  6. const HtmlWebpackPlugin = require("html-webpack-plugin");
  7. const portfinder = require("portfinder"); // 自动检索下一个可用端口
  8. const FriendlyErrorsPlugin = require("friendly-errors-webpack-plugin"); // 友好提示错误信息
  9. const devWebpackConfig = merge(baseWebpackConfig, {
  10. module: {
  11. rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  12. // 自动生成了 css, postcss, less 等规则,与自己一个个手写一样,默认包括了 css 和 postcss 规则
  13. },
  14. devtool: config.dev.devtool,// 添加元信息(meta info)增强调试
  15. // devServer 在 /config/index.js 处修改
  16. devServer: {
  17. clientLogLevel: "warning", // console 控制台显示的消息,可能的值有 none, error, warning 或者 info
  18. historyApiFallback: true, // History API 当遇到 404 响应时会被替代为 index.html
  19. hot: true, // 模块热替换
  20. compress: true, // gzip
  21. host: process.env.HOST || config.dev.host, // process.env 优先
  22. port: process.env.PORT || config.dev.port, // process.env 优先
  23. open: config.dev.autoOpenBrowser, // 是否自动打开浏览器
  24. overlay: config.dev.errorOverlay ? { // warning 和 error 都要显示
  25. warnings: true,
  26. errors: true,
  27. } : false,
  28. publicPath: config.dev.assetsPublicPath, // 配置publicPath
  29. proxy: config.dev.proxyTable, // 代理
  30. quiet: true, // 控制台是否禁止打印警告和错误 若使用 FriendlyErrorsPlugin 此处为 true
  31. watchOptions: {
  32. poll: config.dev.poll, // 文件系统检测改动
  33. }
  34. },
  35. plugins: [
  36. new webpack.DefinePlugin({
  37. "process.env": require("../config/dev.env") // 判断生产环境或开发环境
  38. }),
  39. new webpack.HotModuleReplacementPlugin(), // 热加载
  40. new webpack.NamedModulesPlugin(), // 热加载时直接返回更新的文件名,而不是id
  41. new webpack.NoEmitOnErrorsPlugin(), // 跳过编译时出错的代码并记录下来,主要作用是使编译后运行时的包不出错
  42. new HtmlWebpackPlugin({ // 该插件可自动生成一个 html5 文件或使用模板文件将编译好的代码注入进去
  43. filename: "index.html",
  44. template: "index.html",
  45. inject: true // 可能的选项有 true, "head", "body", false
  46. }),
  47. ]
  48. })
  49. module.exports = new Promise((resolve, reject) => {
  50. portfinder.basePort = process.env.PORT || config.dev.port; // 获取当前设定的端口
  51. portfinder.getPort((err, port) => {
  52. if (err) { reject(err) } else {
  53. process.env.PORT = port; // process 公布端口
  54. devWebpackConfig.devServer.port = port; // 设置 devServer 端口
  55. devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ // 错误提示插件
  56. compilationSuccessInfo: {
  57. messages: [`Your application is running here: http://${config.dev.host}:${port}`],
  58. },
  59. onErrors: config.dev.notifyOnErrors ? utils.createNotifierCallback() : undefined
  60. }))
  61. resolve(devWebpackConfig);
  62. }
  63. })
  64. })
生产模式配置文件 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. const CopyWebpackPlugin = require("copy-webpack-plugin");
  9. const HtmlWebpackPlugin = require("html-webpack-plugin");
  10. const ExtractTextPlugin = require("extract-text-webpack-plugin");
  11. const OptimizeCSSPlugin = require("optimize-css-assets-webpack-plugin");
  12. const env = process.env.NODE_ENV === "production"
  13. ? require("../config/prod.env")
  14. : require("../config/dev.env")
  15. const webpackConfig = merge(baseWebpackConfig, {
  16. module: {
  17. rules: utils.styleLoaders({
  18. sourceMap: config.build.productionSourceMap, // production 下生成 sourceMap
  19. extract: true, // util 中 styleLoaders 方法内的 generateLoaders 函数
  20. usePostCSS: true
  21. })
  22. },
  23. devtool: config.build.productionSourceMap ? config.build.devtool : false,
  24. output: {
  25. path: config.build.assetsRoot,
  26. filename: utils.assetsPath("js/[name].[chunkhash].js"),
  27. chunkFilename: utils.assetsPath("js/[id].[chunkhash].js")
  28. },
  29. plugins: [
  30. new webpack.DefinePlugin({ "process.env": env }),
  31. new webpack.optimize.UglifyJsPlugin({ // js 代码压缩还可配置 include, cache 等,也可用 babel-minify
  32. compress: { warnings: false },
  33. sourceMap: config.build.productionSourceMap,
  34. parallel: true // 充分利用多核cpu
  35. }),
  36. // 提取 js 文件中的 css
  37. new ExtractTextPlugin({
  38. filename: utils.assetsPath("css/[name].[contenthash].css"),
  39. allChunks: false,
  40. }),
  41. // 压缩提取出的css
  42. new OptimizeCSSPlugin({
  43. cssProcessorOptions: config.build.productionSourceMap
  44. ? { safe: true, map: { inline: false } }
  45. : { safe: true }
  46. }),
  47. // 生成 html
  48. new HtmlWebpackPlugin({
  49. filename: process.env.NODE_ENV === "production"
  50. ? config.build.index
  51. : "index.html",
  52. template: "index.html",
  53. inject: true,
  54. minify: {
  55. removeComments: true,
  56. collapseWhitespace: true,
  57. removeAttributeQuotes: true
  58. },
  59. chunksSortMode: "dependency" // 按 dependency 的顺序引入
  60. }),
  61. new webpack.HashedModuleIdsPlugin(), // 根据模块的相对路径生成一个四位数的 hash 作为模块 id
  62. new webpack.optimize.ModuleConcatenationPlugin(), // 预编译所有模块到一个闭包中
  63. // 拆分公共模块
  64. new webpack.optimize.CommonsChunkPlugin({
  65. name: "vendor",
  66. minChunks: function (module) {
  67. return (
  68. module.resource &&
  69. /.js$/.test(module.resource) &&
  70. module.resource.indexOf(
  71. path.join(__dirname, "../node_modules")
  72. ) === 0
  73. )
  74. }
  75. }),
  76. new webpack.optimize.CommonsChunkPlugin({
  77. name: "manifest",
  78. minChunks: Infinity
  79. }),
  80. new webpack.optimize.CommonsChunkPlugin({
  81. name: "app",
  82. async: "vendor-async",
  83. children: true,
  84. minChunks: 3
  85. }),
  86. // 拷贝静态文档
  87. new CopyWebpackPlugin([{
  88. from: path.resolve(__dirname, "../static"),
  89. to: config.build.assetsSubDirectory,
  90. ignore: [".*"]
  91. }])]
  92. })
  93. if (config.build.productionGzip) { // gzip 压缩
  94. const CompressionWebpackPlugin = require("compression-webpack-plugin");
  95. webpackConfig.plugins.push(
  96. new CompressionWebpackPlugin({
  97. asset: "[path].gz[query]",
  98. algorithm: "gzip",
  99. test: new RegExp(".(" + config.build.productionGzipExtensions.join("|") + ")$"),
  100. threshold: 10240, // 10kb 以上大小的文件才压缩
  101. minRatio: 0.8 // 最小比例达到 .8 时才压缩
  102. })
  103. )
  104. }
  105. if (config.build.bundleAnalyzerReport) { // 可视化分析包的尺寸
  106. const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
  107. webpackConfig.plugins.push(new BundleAnalyzerPlugin());
  108. }
  109. module.exports = webpackConfig;
build.js 编译入口

</>复制代码

  1. "use strict"
  2. process.env.NODE_ENV = "production"; // 设置当前环境为生产环境
  3. const ora = require("ora"); //loading...进度条
  4. const rm = require("rimraf"); //删除文件 "rm -rf"
  5. const chalk = require("chalk"); //stdout颜色设置
  6. const webpack = require("webpack");
  7. const path = require("path");
  8. const config = require("../config");
  9. const webpackConfig = require("./webpack.prod.conf");
  10. const spinner = ora("正在编译...");
  11. spinner.start();
  12. // 清空文件夹
  13. rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  14. if (err) throw err;
  15. // 删除完成回调函数内执行编译
  16. webpack(webpackConfig, function (err, stats) {
  17. spinner.stop();
  18. if (err) throw err;
  19. // 编译完成,输出编译文件
  20. process.stdout.write(stats.toString({
  21. colors: true,
  22. modules: false,
  23. children: false,
  24. chunks: false,
  25. chunkModules: false
  26. }) + "
  27. ");
  28. //error
  29. if (stats.hasErrors()) {
  30. console.log(chalk.red(" 编译失败出现错误.
  31. "));
  32. process.exit(1);
  33. }
  34. //完成
  35. console.log(chalk.cyan(" 编译成功.
  36. "))
  37. console.log(chalk.yellow(
  38. " file:// 无用,需http(s)://.
  39. "
  40. ))
  41. })
  42. })

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/89940.html

相关文章

  • vue-cli 3.0 源码分析

    摘要:写在前面其实最开始不是特意来研究的源码,只是想了解下的命令,如果想要了解命令的话,那么绕不开写的。通过分析发现与相比,变化太大了,通过引入插件系统,可以让开发者利用其暴露的对项目进行扩展。 showImg(https://segmentfault.com/img/bVboijb?w=1600&h=1094); 写在前面 其实最开始不是特意来研究 vue-cli 的源码,只是想了解下 n...

    yiliang 评论0 收藏0
  • 从零开始搭建一个vue项目 -- vue-cli/cooking-cli(一)

    摘要:从零开始搭建一个项目一搭建一个可靠成熟的项目介绍我是去年六月份接触的,当时还是个菜逼,当然现在也是,写了一年,抄代码的时候一直是,在别人的框架基础上开发,然后渐渐发现很多的模板都各有优点,所以慢慢的开始集合到了一起。 从零开始搭建一个vue项目 -- vue-cli/cooking-cli(一) 1.vue-cli搭建一个可靠成熟的项目 1.介绍 vue-cli 我是去年六月...

    rainyang 评论0 收藏0
  • ONE-sys 整合前后端脚手架 koa2 + pm2 + vue-cli3.0 + element

    摘要:项目地址干货求本脚手架主要致力于前端工程师的快速开发一键部署等快捷开发框架,主要目的是想让前端工程师在一个阿里云服务器上可以快速开发部署自己的项目。 项目地址https://github.com/fanshyiis/... 干货!求star showImg(https://segmentfault.com/img/remote/1460000017886870); 本脚手架主要致力于...

    刘福 评论0 收藏0
  • vue-cli#4.7项目结构分析

    摘要:前言使用过进行项目开发的同学,一定知道或者使用过脚手架,他能够很好的搭建项目结构和工程,让我们能够把足够的精力放在业务开发上。对象提供一系列属性,用于返回系统信息返回当前进程的命令行参数数组。 前言 使用过 vue 进行项目开发的同学,一定知道或者使用过 vue-cli 脚手架,他能够很好的搭建项目结构和工程,让我们能够把足够的精力放在业务开发上。也正是因为这样,很多时候我们会因为项目...

    EastWoodYang 评论0 收藏0
  • 使用vue-cli脚手架+webpack搭建vue项目

    摘要:查看安装是否正常回车后看到输出当前安装的版本号,例如,即安装正常通过以上步聚,说明已经安装完并能正常运行。再次用脚手架搭建项目第二步将模块安装完成后,就可以使用以下命令创建项目了。 前言 世间万难 无非一拖二懒三不读书 对 说的就是我 突然觉得这句话说的很对,自从上次写完nodejs安装及npm全局模块路径的设置已经过去两月有余,而我的vue框架学习也就止步于此。还是没有给自己施加压力...

    dantezhao 评论0 收藏0

发表评论

0条评论

LoftySoul

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<