likes
comments
collection
share

webpack

作者站长头像
站长
· 阅读数 20

3.1 Vue2

3.1.1 使用vue-cli2版本创建vue项目

因为我原来的vue-cli版本比较高,所以我先卸载高版本的

👉vue脚手架vue-cli的卸载与安装方式

3.1.1.1 卸载版本

/卸载3.0之前的版本
npm uninstall -g vue-cli
yarn global remove vue-cli
//卸载3.0之后的版本(可以统一使用此指令卸载)
npm uninstall -g @vue/cli
yarn global remove @vue/cli

3.1.1.2 安装最新版本

// 安装最新版本
npm install -g @vue/cli
或者
yarn global add @vue/cli
// 安装vue-cli2的版本
npm install -g vue-cli

3.1.1.3 安装指定版本

//安装2.9.6版本
npm install -g vue-cli@2.9.6
yarn global add vue-cli@2.9.6
//安装3.0.3版本
npm install -g @vue/cli@3.0.3
yarn global add @vue/cli@3.0.3
//安装4.0.5版本
npm install -g @vue/cli@4.0.5
yarn global add @vue/cli@4.0.5

3.1.1.4 安装过程

安装完脚手架之后,就使用vue-cli2创建项目的命令,初始化一个项目,我没有安装webpack,我想看看它能不能跑 vue init webpack vue-cli2的脚手架的vue项目

webpack

使用npm run dev启动项目,项目成功启动

webpack

3.1.1.5 目录结构

webpack

vue-cli2基于的webpack版本

webpack

build

webpack

build.js
'use strict' // 严格模式
require('./check-versions')() // 引入检查版本的文本并且立即执行
process.env.NODE_ENV = 'production' // 设置环境是生产环境(服务器) development是开发环境(本地)
const ora = require('ora') // ora包⽤于显⽰加载中的效果,类似于前端页⾯的loading效果
const rm = require('rimraf') // 以包的形式包装••rm -rf••命令,用来删除文件和文件夹的
const path = require('path') // path 模块提供了用于处理文件和目录的路径的实用工具
const chalk = require('chalk') // chalk是一个可以修改终端输出字符样式的npm包
const webpack = require('webpack')
const config = require('../config') //  引入项目中的config 目录
const webpackConfig = require('./webpack.prod.conf') // 引入webpack中生产环境配置
const spinner = ora('building for production...') // 打包时会显示的提示语
spinner.start() // 开始执行加载动画
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  // 删除dist以及static目录及所有文件
  if (err) throw err
  webpack(webpackConfig, (err, stats) => {
    spinner.stop()
    if (err) throw err
    process.stdout.write(
      // process.stdout.write与console.log相似
      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'
    )
    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"
      )
    )
  })
})

check-versions.js
'use strict'
const chalk = require('chalk') // chalk是一个可以修改终端输出字符样式的npm包
const semver = require('semver') // semver模块是一个专门处理与版本相关的工具包
const packageConfig = require('../package.json') // 应用包管理文件
const shell = require('shelljs') // 用来执行unix命令的包。
//封装方法 用来获取纯净的版本号
//child_process是node用来创建子进程 execSync是创建同步进程
function exec(cmd) {
  return require('child_process')
    .execSync(cmd)
    .toString()
    .trim()
}

const versionRequirements = [
  {
    name: 'node',
    // 当前的node版本号
    currentVersion: semver.clean(process.version),
    // 要求的node版本号
    versionRequirement: packageConfig.engines.node
  }
]

if (shell.which('npm')) {
  // 将npm添加到versionRequirements中
  versionRequirements.push({
    name: 'npm',
    // 当前的npm版本
    currentVersion: exec('npm --version'),
    // 要求的npm版本
    versionRequirement: packageConfig.engines.npm
  })
}

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

  for (let i = 0; i < versionRequirements.length; i++) {
    const mod = versionRequirements[i]
    // 如果当前版本号不符合要求的版本号,那么就将提示信息添加到wranings
    if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
      warnings.push(
        mod.name +
          ': ' +
          chalk.red(mod.currentVersion) +
          ' should be ' +
          chalk.green(mod.versionRequirement)
      )
    }
  }
  // 如果有warnings 那么就打印出来
  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)
  }
}

utils.js
'use strict'
const path = require('path') //导入path
const config = require('../config') // 导入config文件
const ExtractTextPlugin = require('extract-text-webpack-plugin') // 导入extract-text-webpack-plugin 用来抽离css 防止css打包压缩到js中
const packageConfig = require('../package.json') // 导入包管理文件

exports.assetsPath = function(_path) {
  const assetsSubDirectory =
    process.env.NODE_ENV === 'production' // 生产环境
      ? config.build.assetsSubDirectory
      : config.dev.assetsSubDirectory
  // path.posix是处理跨操作系统 path.join是用\拼接路径片
  return path.posix.join(assetsSubDirectory, _path)
}

exports.cssLoaders = function(options) {
  options = options || {}
  // 该cssLoaders是为了下面的styleLoaders服务
  const cssLoader = {
    loader: 'css-loader',
    options: {
      // 是否开启sourceMap 用来调试
      sourceMap: options.sourceMap
    }
  }
  // postcssLoader基本配置 用来添加浏览器前缀
  const postcssLoader = {
    loader: 'postcss-loader',
    options: {
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  // 封装函数 添加相应的css预处理器的插件
  function generateLoaders(loader, loaderOptions) {
    // 将上面的cssLoader放在一个数组中
    const loaders = options.usePostCSS
      ? [cssLoader, postcssLoader]
      : [cssLoader]
    // 如果该函数传达了loader那就添加到loaders中,该loader可能是less/sass等
    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    // 根据是否抽离css 返回最终读取和导入loader 来处理对应类型的文件
    // 是否抽离css
    if (options.extract) {
      // 提取抽离css
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      // 不抽离
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  // css预加载器
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

// 主要处理Import方式导入的文件类型的打包,上面的cssLoaders是为这步服务
// 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
    })
  }

  return output
}
// 消息通知
exports.createNotifierCallback = () => {
  const notifier = require('node-notifier')

  return (severity, errors) => {
    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')
    })
  }
}
vue-loader.conf.js
'use strict'
const utils = require('./utils') // 导入utils文件
const config = require('../config') // 导入config文件夹
const isProduction = process.env.NODE_ENV === 'production' // 是否是生产环境(线上环境)
// 根据环境来获取相应的productionSourceMap或者cssSourceMap
const sourceMapEnabled = isProduction
  ? config.build.productionSourceMap
  : config.dev.cssSourceMap

module.exports = {
  loaders: utils.cssLoaders({
    // 是否开始sourceMap 用来调试
    sourceMap: sourceMapEnabled,
    // 是否单独提取抽离css
    extract: isProduction
  }),
  cssSourceMap: sourceMapEnabled,
  cacheBusting: config.dev.cacheBusting,
  // 在模版编译过程中,编译器可以将某些属性,如 src 路径,转换为require调用,以便目标资源可以由 webpack 处理.
  transformToRequire: {
    video: ['src', 'poster'],
    source: 'src',
    img: 'src',
    image: 'xlink:href'
  }
}
webpack.base.conf.js
'use strict'
const path = require('path')
const utils = require('./utils')
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: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    // 静态资源路径 根据环境来改变
    publicPath:
      process.env.NODE_ENV === 'production'
        ? config.build.assetsPublicPath
        : config.dev.assetsPublicPath
  },
  // 对模块进行解析
  resolve: {
    // 对模块的后缀进行解析 比如导入index 没有写后缀名 那么会自动先匹配.js>.vue>.json后缀文件
    extensions: ['.js', '.vue', '.json'],
    // 别名
    alias: {
      '@': resolve('src')
    }
  },
  // 解析不同的模块
  module: {
    rules: [
      {
        test: /.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /.js$/,
        loader: 'babel-loader',
        // 解析的包含的文件路径
        include: [
          resolve('src'),
          resolve('test'),

          resolve('node_modules/webpack-dev-server/client')
        ]
      },
      {
        test: /.(png|jpe?g|gif|svg)(?.*)?$/,
        // 用url-loader去解析图片资源
        loader: 'url-loader',
        options: {
          limit: 10000,
          // 对输出的内容进行地址转换
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      // 解析视频音频
      {
        test: /.(mp4|webm|ogg|mp3|wav|flac|aac)(?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      // 解析字体文件
      {
        test: /.(woff2?|eot|ttf|otf)(?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  node: {
    // 阻止webpack注入无用的setImmediate polyfill
    // 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'
  }
}
webpack.dev.conf.js
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
// 导入webpackage-merge 用来合并对象 去掉重复的属性
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
// 导入copy-webpack-plugin 用来复制
const CopyWebpackPlugin = require('copy-webpack-plugin')
// 导入html-webpack-plugin 用来自动生成html
const HtmlWebpackPlugin = require('html-webpack-plugin')
// 导入friendily-errors-webpack-plugin 用来收集和展示错误日志
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// 导入portfinder 用来获取port
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    // 解析样式文件的规则
    rules: utils.styleLoaders({
      sourceMap: config.dev.cssSourceMap,
      usePostCSS: true
    })
  },
  // cheap-module-eval-source-map is faster for development
  // 开发工具 用来调试
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  // 服务器
  devServer: {
    clientLogLevel: 'warning',
    // HTML5 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.
    // 是否压缩
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    // 自动打开浏览器
    open: config.dev.autoOpenBrowser,
    // 编译出错时是否有提示
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    // 静态资源路径 此路径可在浏览器中打开
    publicPath: config.dev.assetsPublicPath,
    // 代理
    proxy: config.dev.proxyTable,
    // 启用quiet 意思是除了启动信息以外的任何信息都不会打印在控制台
    quiet: true, // necessary for FriendlyErrorsPlugin
    // 监视文件的选项
    watchOptions: {
      poll: config.dev.poll
    }
  },
  // 插件
  plugins: [
    // 自定义一个plugin 生成当前环境的一个变量
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    // 模块热替换插件 修改模块时不需要刷新页面
    new webpack.HotModuleReplacementPlugin(),
    // 当开启HMR的时候使用该插件会显示模块的相对路径
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    // 在编译出错时 使用NoEmitOnErrorsPlugin来跳过输出阶段 确保输出资源不会包含错误
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    // 自动生成html
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    // 复制静态资源到开发环境的路径
    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 {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      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)
    }
  })
})
webpack.prod.conf.js
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin') // 抽离css
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') // 压缩css代码
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') // 丑化压缩JS代码

const env = require('../config/prod.env') // 导入环境变量

const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  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: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      // 并行提高效率,并行数量与CPU的数量(默认为os.cpus().length - 1,也可以手动指定数量)相关。
      parallel: true
    }),
    // extract css into its own file
    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 }
    }),
    // generate dist index.html with correct asset hash for caching.
    // you can customize output by editing /index.html
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'index.html',
      // 将js文件放到body标签的结尾(默认值),也可以选择插入到head中或者不插入
      inject: true,
      minify: {
        // 删除index.html中的注释
        removeComments: true,
        // 删除index.html中的空格
        collapseWhitespace: true,
        // 删除各种html标签属性值的双引号
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      // 确定script插入的顺序,dependency表示按照文件的依赖顺序进行处理
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vendor modules does not change
    new webpack.HashedModuleIdsPlugin(),
    // enable scope hoisting
    // 预编译提升代码在浏览器中的执行速度
    new webpack.optimize.ModuleConcatenationPlugin(),
    // split vendor js into its own file
    // 主要是用来提取第三方库和公共模块
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks(module) {
        // any required modules inside node_modules are extracted to vendor
        return (
          // "有正在处理文件" + "这个文件是 .js 后缀" + "这个文件是在 node_modules 中"
          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个chunks公共引用,才会被抽取出来为common chunk
      minChunks: 3
    }),

    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  // 开启Gzi压缩打包后的文件,把这个压缩包给浏览器,浏览器自动解压
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\.(' + config.build.productionGzipExtensions.join('|') + ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  // 打包编译后的文件打印出详细的文件信息,vue-cli默认把这个禁用了,个人觉得还是有点用的,可以自行配置
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
    .BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig
config

webpack

dev.env.js
'use strict' //此文件时开发环境配置文件
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
// 合并两个配置文件对象并生成一个新的配置文件,如果合并的过程中遇到冲突的属性,第二个参数的属性会覆盖第一个参数的属性,减少重复代码
module.exports = merge(prodEnv, {
  NODE_ENV: '"development"'
})
index.js
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static', // 编译输出的二级目录
    assetsPublicPath: '/', // 编译发布的根目录,可配置为资源服务器域名或 CDN 域名
    proxyTable: {}, // 需要 proxyTable 代理的接口(可跨域)

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false, // 自动打开浏览器
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    
    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    // 编译输入的 index.html 文件, __dirname 是node的一个全局变量,获得当前文件所在目录的完整目录名
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'), // 编译输出的静态资源路径
    assetsSubDirectory: 'static', // 编译输出的二级目录
    assetsPublicPath: '/',// 编译发布的根目录,可配置为资源服务器域名或 CDN 域名

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}
prod.env.js
'use strict'
module.exports = {
  NODE_ENV: '"production"' // 开发环境
}

3.1.1.6 assets 和static的区别

assets和static都是放置静态文件的地方

不同的是,assets中的文件在打包时会进行压缩或者格式化的处理,体积会小一些。然后进入到static文件和index.html一起上传到服务器,但是static中的文件不会进行压缩和格式化的处理。相对体积会大一些

需要压缩的css和js文件可以放入assets中,进行压缩减少体积,但是第三方引入的iconfont等文件就直接放入static中,因为第三方的文件已经处理过了。

3.1.1.7 打包结果

css文件

webpack

js文件

webpack