webpack打包文件build.js解读

webpack打包文件build.js解读,build.js通过package.json中的script来执行脚本:npm run build。一般build.js都是以下结构:

require('./check-versions')()

//process.env是一个包含用户环境信息的对象 NODE_ENV是用户自定义的变量,用来判断是开发环境还是生产环境
process.env.NODE_ENV = process.argv.splice(2)[0] == 'dev' ? 'development' : 'production'

var ora = require('ora')   //ora:https://www.npmjs.com/package/ora  ora包用于显示加载中的效果,类似于前端页面的loading效果
var rm = require('rimraf') //rimraf模块 以包的形式包装rm -rf命令,用来删除文件和文件夹的,不管文件是否为空
var path = require('path')  //导入node的path模块
var chalk = require('chalk') //地址:https://www.npmjs.com/package/chalk 导入chalk模块 用来改变文字颜色
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')

var spinner = ora(process.env.NODE_ENV == 'production' ? 'building for production...' : 'building for development...')
spinner.start()

//rm方法删除static文件夹
//path.join是将路径片段以'\'连接成新的路径,任何一个路径片段有错误就会报错
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
   //构建webpack
  webpack(webpackConfig, function (err, stats) {
    //停止动画
    spinner.stop()
    if (err) throw err
    //process.stdout.write是标准输出,相当于console.log
    process.stdout.write(stats.toString({
       //增加控制卡颜色开关,即显示不同颜色的字体
           colors:true,
           //是否增加内置模块信息
           modules:false,
           children:false,
           //允许较少的输出
           chunks:false,
           //不将内置模块的信息加到包信息
           chunkModules:false

    }) + '\n\n')
    //编译退出
    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'
    ))
  })
})

关于process.argv.splice(2)[0]定义环境:

  • nodejs通过process.argv设置参数,进行定制化webpack编译

    命令行

    npm run build --dev
    npm run build --qa
    npm run build --production
    

    webpack.config.js

    process.argv.splice(2)[0] ;//dev ,qa,production

 

你可能感兴趣的:(webpack打包文件build.js解读)