Vue-cli 命令行工具项目配置源码解析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qishuixian/article/details/80530594

我们都知道vue cli是vue.js 提供一个官方搭建项目命令行工具,可用于快速搭建大型单页应用。以下是Vue-cli @2.9搭建项目的配置源码解析

相关目录

├── build
│  ├── build.js
│  ├── utils.js
│  ├── check-versions.js
│  ├── vue-loader.conf.js
│  ├── webpack.base.conf.js
│  ├── webpack.dev.conf.js
│  └── webpack.prod.conf.js
├── config
│  ├── dev.env.js
│  ├── index.js
│  └── prod.env.js

一、build目录

    1、build.js(编译入口)

'use strict'
/*
 * 编译入口
 *
*/
require('./check-versions')()
// 设置当前环境为生产环境
process.env.NODE_ENV = 'production'
//loading...进度条
const ora = require('ora')
//删除文件 'rm -rf'
const rm = require('rimraf')
// 使用 NodeJS 自带的文件路径工具
const path = require('path')
//stdout颜色设置
const chalk = require('chalk')
// 使用 webpack
const webpack = require('webpack')
// 获取 config/index.js 的默认配置
const config = require('../config')
// 加载 webpack.base.conf
const webpackConfig = require('./webpack.prod.conf')

const spinner = ora('building for production...')
spinner.start()
// 清空文件夹
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
  // 删除完成回调函数内执行编译
  webpack(webpackConfig, (err, stats) => {
    spinner.stop()
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
      chunks: false,
      chunkModules: false
    }) + '\n\n')
     //error
    if (stats.hasErrors()) {
      console.log(chalk.red('  Build failed with errors.\n'))
      process.exit(1)
    }
   //完成
    console.log(chalk.cyan('  Build complete.\n'))
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
  })
})

2、check-versions.js( 版本验证工具)

'use strict'
/*
 * 版本验证工具
 *
*/

//引入的是一个用来在命令行输出不同颜色文字的模块,通过chalk.yellow("想添加颜色的文字......")来实现改变文字颜色的;
const chalk = require('chalk')
//引入的是一个语义化版本文件的npm包,其实它就是用来控制版本的
const semver = require('semver')
const packageConfig = require('../package.json')
//用来执行unix命令的包。
const shell = require('shelljs')

// 脚本可以通过 child_process 模块新建子进程,从而执行 Unix 系统命令
//下面这段代码实际就是把cmd这个参数传递的值,转化成前后没有空格的字符串,也就是版本号
function exec (cmd) {
  return require('child_process').execSync(cmd).toString().trim()
}

const versionRequirements = [
  {
    name: 'node',
    // 当前环境版本,使用semver插件把当前环境版本信息转化成规定格式,也就是 ‘  =v1.2.3  ‘ -> ‘1.2.3‘ 这种功能
    currentVersion: semver.clean(process.version),
      // 要求的版本,这是规定的pakage.json中engines选项的node版本信息 "node":">= 4.0.0"
    versionRequirement: packageConfig.engines.node
  }
]
// npm环境中
if (shell.which('npm')) {
  versionRequirements.push({
    name: 'npm',
    // 执行方法得到版本号
    currentVersion: exec('npm --version'),
    // 要求的版本
    versionRequirement: packageConfig.engines.npm
  })
}

module.exports = function () {
  const warnings = []

  for (let i = 0; i < versionRequirements.length; i++) {
    const mod = versionRequirements[i]
      //上面这个判断就是如果版本号不符合package.json文件中指定的版本号,就执行下面的代码
    if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
      warnings.push(mod.name + ': ' +
        chalk.red(mod.currentVersion) + ' should be ' +
        chalk.green(mod.versionRequirement)
      )
    }
  }

  if (warnings.length) {
    console.log('')
    console.log(chalk.yellow('To use this template, you must update following to modules:'))
    console.log()

    for (let i = 0; i < warnings.length; i++) {
      const warning = warnings[i]
      console.log('  ' + warning)
    }

    console.log()
    process.exit(1)
  }
}

3、utils.js(实用代码段)

'use strict'
/*
 * 实用代码段
 *
*/
// 使用 NodeJS 自带的文件路径工具
const path = require('path')
// 获取 config/index.js 的默认配置
const config = require('../config')
//该插件的主要是为了抽离css样式,防止将样式打包在js中引起页面样式加载错乱的现象(提取样式插件)
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')

exports.assetsPath = function (_path) {
  const assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory  //'static'
    : config.dev.assetsSubDirectory
  // posix方法修正路径
  return path.posix.join(assetsSubDirectory, _path)
}

exports.cssLoaders = function (options) {
    // 示例: ({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  options = options || {}
   // cssLoader
  const cssLoader = {
    loader: 'css-loader',
    options: {
      sourceMap: options.sourceMap
    }
  }
    // postcssLoader
  const postcssLoader = {
    loader: 'postcss-loader',
    options: {
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {
      // 设置默认loader
    const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]

    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        // 生成 options 对象
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // 生产模式中提取css
    // 如果 options 中的 extract 为 true 配合生产模式
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        // 默认使用 vue-style-loader
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // 返回各种 loaders 对象
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
  // 示例:[
  // { loader: 'css-loader', options: { sourceMap: true/false } },
  // { loader: 'postcss-loader', options: { sourceMap: true/false } },
  // { loader: 'less-loader', options: { sourceMap: true/false } },
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  const output = []
  const loaders = exports.cssLoaders(options)

  for (const extension in loaders) {
    const loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  // 示例:
  // {
  //  test: new RegExp(\\.less$),
  //  use: {
  //   loader: 'less-loader', options: { sourceMap: true/false }
  //  }
  // }
  }

  return output
}
// 配合 friendly-errors-webpack-plugin
exports.createNotifierCallback = () => {
  // 基本用法:notifier.notify('message');
  // 发送跨平台通知系统
  const notifier = require('node-notifier')

  return (severity, errors) => {
    // 当前设定是只有出现 error 错误时触发 notifier 发送通知
      // 严重程度可以是 'error' 或 'warning'
    if (severity !== 'error') return

    const error = errors[0]
    const filename = error.file && error.file.split('!').pop()

    notifier.notify({
      title: packageConfig.name,
      message: severity + ': ' + error.name,
      subtitle: filename || '',
      // 通知图标
      icon: path.join(__dirname, 'logo.png')
    })
  }
}

4、vue-loader.conf.js(webpack的loader加载器)

'use strict'
/*
 * webpack的loader加载器。
 *
*/
// 使用一些小工具
const utils = require('./utils')
// 获取 config/index.js 的默认配置
const config = require('../config')
//判断是否是产品环境
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
  ? config.build.productionSourceMap
  : config.dev.cssSourceMap

module.exports = {
  // 处理.vue文件中的样式
  loaders: utils.cssLoaders({
      // 是否打开source-map
    sourceMap: sourceMapEnabled,
      // 是否提取样式到单独的文件
    extract: isProduction
  }),
  cssSourceMap: sourceMapEnabled,
   // 缓存破坏,特别是进行sourceMap debug时,设置成false是非常有帮助的
  cacheBusting: config.dev.cacheBusting,
  // 转化请求的内容,video、source、img、image等的属性进行配置
  transformToRequire: {
    video: ['src', 'poster'],
    source: 'src',
    img: 'src',
    image: 'xlink:href'
  }
}

5、webpack.base.conf.js(基础配置文件)

'use strict'
/*
 * 基础配置文件
 *
*/
// 使用 NodeJS 自带的文件路径工具
const path = require('path')
// 使用一些小工具
const utils = require('./utils')
// 获取 config/index.js 的默认配置
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}



module.exports = {
    // 基础目录
  context: path.resolve(__dirname, '../'),
  entry: {
    // 编译文件入口
    app: './src/main.js'
  },
  output: {
   //编译输出的静态资源根路径  默认'../dist'
    path: config.build.assetsRoot,
   // 编译输出的文件名
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath //生产模式publicpath
      : config.dev.assetsPublicPath   //开发模式publicpath
  },
  resolve: {
    // 解析确定的拓展名,方便模块导入
    extensions: ['.js', '.vue', '.json'],
    alias: {
      // 创建别名
      'vue$': 'vue/dist/vue.esm.js',
        // 如 '@/components/HelloWorld'
      '@': resolve('src'),
    }
  },
  module: {
    rules: [
      {
        // vue 要在babel之前
        test: /\.vue$/,
        loader: 'vue-loader',
        //可选项: vue-loader 选项配置
        options: vueLoaderConfig
      },
      {
       // babel
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        // url-loader 文件大小低于指定的限制时,可返回 DataURL,即base64
        // url-loader 图片
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        // 兼容性问题需要将query换成options
        options: {
          // 默认无限制
          limit: 10000,
           // hash:7 代表 7 位数的 hash
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
         // url-loader 音视频
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        // url-loader 字体
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
 // 是否 polyfill 或 mock
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

6、webpack.dev.conf.js(开发模式配置文件)

'use strict'
/*
 * 开发模式配置文件
 *
*/
// 使用一些小工具
const utils = require('./utils')
// 使用 webpack
const webpack = require('webpack')
// 获取 config/index.js 的默认配置
const config = require('../config')
// 使用 webpack 配置合并插件
const merge = require('webpack-merge')
// 使用 NodeJS 自带的文件路径工具
const path = require('path')
// 加载 webpack.base.conf
const baseWebpackConfig = require('./webpack.base.conf')
//在webpack中拷贝文件和文件夹
const CopyWebpackPlugin = require('copy-webpack-plugin')
 // 使用 html-webpack-plugin 插件,这个插件可以帮我们自动生成 html 并且注入到 .html 文件中
const HtmlWebpackPlugin = require('html-webpack-plugin')
// webpack错误信息提示插件
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
//查看进程端口
const portfinder = require('portfinder')
//电脑默认的域名
const HOST = process.env.HOST
//电脑默认的端口
const PORT = process.env.PORT && Number(process.env.PORT)
 // 将我们 webpack.dev.conf.js 的配置和 webpack.base.conf.js 的配置合并
const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
   // 自动生成了 css, postcss, less 等规则,与自己一个个手写一样,默认包括了 css 和 postcss 规则
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // 使用 cheap-module-eval-source-map 模式作为开发工具 添加元信息(meta info)增强调试
  devtool: config.dev.devtool,
  // these devServer options should be customized in /config/index.js
  devServer: {
    // console 控制台显示的消息,可能的值有 none, error, warning 或者 info
    clientLogLevel: 'warning',
    // History API 当遇到 404 响应时会被替代为 index.html
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    // 模块热替换
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    // gzip
    compress: true,
    // process.env 优先
    host: HOST || config.dev.host,
    // process.env 优先
    port: PORT || config.dev.port,
    // 是否自动打开浏览器
    open: config.dev.autoOpenBrowser,
    // warning 和 error 都要显示
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    // 配置publicPath
    publicPath: config.dev.assetsPublicPath,
    // 代理
    proxy: config.dev.proxyTable,
    // 控制台是否禁止打印警告和错误 若使用 FriendlyErrorsPlugin 此处为 true
    quiet: true,
    watchOptions: {
      // 文件系统检测改动
      poll: config.dev.poll,
    }
  },
  plugins: [
    new webpack.DefinePlugin({
        // 判断生产环境或开发环境
      'process.env': require('../config/dev.env')
    }),
    // 热加载
    new webpack.HotModuleReplacementPlugin(),
    // 热加载时直接返回更新的文件名,而不是id
    new webpack.NamedModulesPlugin(),
    // 跳过编译时出错的代码并记录下来,主要作用是使编译后运行时的包不出错
    new webpack.NoEmitOnErrorsPlugin(),
    // 该插件可自动生成一个 html5 文件或使用模板文件将编译好的代码注入进去
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      // 可能的选项有 true, 'head', 'body', false
      inject: true
    }),
    //拷贝文件和文件夹
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  //获取当前设定的端口
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // process 公布端口
      process.env.PORT = port
      // 设置 devServer 端口
      devWebpackConfig.devServer.port = port

      // 错误提示插件
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})

7、webpack.prod.conf.js(生产模式配置文件)

'use strict'
/*
* 生产模式配置文件
*
 */

// 使用 NodeJS 自带的文件路径工具
const path = require('path')
// 使用一些小工具
const utils = require('./utils')
// 使用 webpack
const webpack = require('webpack')
// 获取 config/index.js 的默认配置
const config = require('../config')
// 使用 webpack 配置合并插件
const merge = require('webpack-merge')
// 加载 webpack.base.conf
const baseWebpackConfig = require('./webpack.base.conf')
//在webpack中拷贝文件和文件夹
const CopyWebpackPlugin = require('copy-webpack-plugin')
// 使用 html-webpack-plugin 插件,这个插件可以帮我们自动生成 html 并且注入到 .html 文件中
const HtmlWebpackPlugin = require('html-webpack-plugin')
//该插件的主要是为了抽离css样式,防止将样式打包在js中引起页面样式加载错乱的现象(提取样式插件)
const ExtractTextPlugin = require('extract-text-webpack-plugin')
//压缩提取出的css,并解决ExtractTextPlugin分离出的js重复问题(多个文件引入同一css文件)
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
//压缩js
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
//产品环境
const env = require('../config/prod.env')
// 合并 webpack.base.conf.js
const webpackConfig = merge(baseWebpackConfig, {
  module: {
    // 自动生成了 css, postcss, less 等规则,与自己一个个手写一样,默认包括了 css 和 postcss 规则
    rules: utils.styleLoaders({
      // production 下生成 sourceMap
      sourceMap: config.build.productionSourceMap,
      // util 中 styleLoaders 方法内的 generateLoaders 函数
      extract: true,
      usePostCSS: true
    })
  },
  // 是否使用 cheap-module-eval-source-map 模式作为开发工具
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
    // 编译输出目录
    path: config.build.assetsRoot,
    // 编译输出文件名
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    //没有指定输出名的文件输出的文件名
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
   // definePlugin 接收字符串插入到代码当中, 所以你需要的话可以写上 JS 的字符串
    new webpack.DefinePlugin({
      'process.env': env
    }),
    // 压缩 js (同样可以压缩 css)
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    // 将 css 文件分离出来
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      // Setting the following option to `false` will not extract CSS from codesplit chunks.
      // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
      // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
      // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
      allChunks: true,
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      cssProcessorOptions: config.build.productionSourceMap
        ? { safe: true, map: { inline: false } }
        : { safe: true }
    }),
    // 构建要输出的 index.html 文件, HtmlWebpackPlugin 可以生成一个 html 并且在其中插入你构建生成的资源
    new HtmlWebpackPlugin({
      // 生成的 html 文件名
      filename: config.build.index,
      // 使用的模板
      template: 'index.html',
      // 是否注入 html (有多重注入方式,可以选择注入的位置)
      inject: true,
      //压缩的方式
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vendor modules does not change
    new webpack.HashedModuleIdsPlugin(),
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),
    //  CommonsChunkPlugin用于生成在入口点之间共享的公共模块(比如jquery,vue)的块并将它们分成独立的包。
    // 而为什么要new两次这个插件,这是一个很经典的bug的解决方案,
    // 在webpack的一个issues有过深入的讨论webpack/webpack#1315 .----为了将项目中的第三方依赖代码抽离出来,
    // 官方文档上推荐使用这个插件,当我们在项目里实际使用之后,
    // 发现一旦更改了 app.js 内的代码,vendor.js 的 hash 也会改变,那么下次上线时,
    // 用户仍然需要重新下载 vendor.js 与 app.js
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks (module) {
        // 依赖的 node_modules 文件会被提取到 vendor 中
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    // This instance extracts shared chunks from code splitted chunks and bundles them
    // in a separate chunk, similar to the vendor chunk
    // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
    new webpack.optimize.CommonsChunkPlugin({
      name: 'app',
      async: 'vendor-async',
      children: true,
      minChunks: 3
    }),

    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})
 // 开启 gzip 的情况下使用下方的配置
if (config.build.productionGzip) {
  //  加载 compression-webpack-plugin 插件
  const CompressionWebpackPlugin = require('compression-webpack-plugin')
  // 向webpackconfig.plugins中加入下方的插件
  webpackConfig.plugins.push(
    // 使用 compression-webpack-plugin 插件进行压缩
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      // 10kb 以上大小的文件才压缩
      threshold: 10240,
      // 最小比例达到 .8 时才压缩
      minRatio: 0.8
    })
  )
}
// 可视化分析包的尺寸
if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

二、config目录

    1、dev.env.js(开发模式)

'use strict'
/*
 * 开发模式
 *
*/
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"'
})
'use strict'
/*
 * 配置文件
 *
*/
// 使用 NodeJS 自带的文件路径工具
const path = require('path')

module.exports = {
  dev: {

    // 路径
    // path:用来存放打包后文件的输出目录
    assetsSubDirectory: 'static',
    // publicPath:指定资源文件引用的目录
    assetsPublicPath: '/',
    // 代理示例: proxy: [{context: ["/auth", "/api"],target: "http://localhost:3000",}]
    proxyTable: {},
    // 开发服务器变量设置
    host: 'localhost',
    port: 8080,
    // 开发服务器变量设置
    autoOpenBrowser: true,
    // 浏览器错误提示 devServer.overlay
    errorOverlay: true,
    // 配合 friendly-errors-webpack-plugin
    notifyOnErrors: true,
   // 使用文件系统(file system)获取文件改动的通知devServer.watchOptions
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-


    /**
     * Source Maps
     */

    // // 增强调试 可能的推荐值:eval, eval-source-map(推荐),
    // cheap-eval-source-map, cheap-module-eval-source-map
    // 详细:<a rel="nofollow" href="https://doc.webpack-china.org/configuration/devtool" target="_blank">
    // https://doc.webpack-china.org/configuration/devtool</a>
    devtool: 'cheap-module-eval-source-map',

    //缓存破坏设置
    cacheBusting: true,
    // develop 下不生成 sourceMap
    cssSourceMap: true
  },

  build: {
    // index模板文件
    index: path.resolve(__dirname, '../dist/index.html'),

    // 路径
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */
    // production 下是生成 sourceMap
    productionSourceMap: true,
   // devtool: 'source-map' ?
    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
  }
}

2、index.js配置文件)
'use strict'
/*
 * 配置文件
 *
*/
// 使用 NodeJS 自带的文件路径工具
const path = require('path')

module.exports = {
  dev: {

    // 路径
    // path:用来存放打包后文件的输出目录
    assetsSubDirectory: 'static',
    // publicPath:指定资源文件引用的目录
    assetsPublicPath: '/',
    // 代理示例: proxy: [{context: ["/auth", "/api"],target: "http://localhost:3000",}]
    proxyTable: {},
    // 开发服务器变量设置
    host: 'localhost',
    port: 8080,
    // 开发服务器变量设置
    autoOpenBrowser: true,
    // 浏览器错误提示 devServer.overlay
    errorOverlay: true,
    // 配合 friendly-errors-webpack-plugin
    notifyOnErrors: true,
   // 使用文件系统(file system)获取文件改动的通知devServer.watchOptions
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-


    /**
     * Source Maps
     */

    // // 增强调试 可能的推荐值:eval, eval-source-map(推荐),
    // cheap-eval-source-map, cheap-module-eval-source-map
    // 详细:<a rel="nofollow" href="https://doc.webpack-china.org/configuration/devtool" target="_blank">
    // https://doc.webpack-china.org/configuration/devtool</a>
    devtool: 'cheap-module-eval-source-map',

    //缓存破坏设置
    cacheBusting: true,
    // develop 下不生成 sourceMap
    cssSourceMap: true
  },

  build: {
    // index模板文件
    index: path.resolve(__dirname, '../dist/index.html'),

    // 路径
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */
    // production 下是生成 sourceMap
    productionSourceMap: true,
   // devtool: 'source-map' ?
    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
  }
}

3、prod.env.js(生产模式)

'use strict'
/*
 * 生产模式
 *
*/
module.exports = {
  NODE_ENV: '"production"'
}

猜你喜欢

转载自blog.csdn.net/qishuixian/article/details/80530594
今日推荐