详解Webpack多环境代码打包的方法


Posted in Javascript onAugust 03, 2018

在实际开发中常遇到,代码在

在package.json文件的scripts中,会提供开发环境与生产环境两个命令。但是实际使用中会遇见 测试版与正式版代码相继发布的情况,这样反复更改服务器地址,偶尔忘记更改url会给工作带来很多不必要的麻烦(当然也会对你的工作能力产生质疑)。这样就需要在生产环境中配置测试版本打包命令与正式版本打包命令。

1、Package.json 文件中 增加命令行命令,并指定路径。

"scripts": {
  "dev": "node build/dev-server.js",
  "build": "node build/build.js",

//正式环境打包命令
  "fev": "node build/test.js"       //测试环境打包命令
 },

2、在build文件中添加相应文件

详解Webpack多环境代码打包的方法

test.js

// https://github.com/shelljs/shelljs
require('./check-versions')()

process.env.NODE_ENV = 'fev'

var ora = require('ora')
var path = require('path')
var chalk = require('chalk')
var shell = require('shelljs')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.test.conf')

var spinner = ora('building for fev...')
spinner.start()

var assetsPath = path.join(config.fev.assetsRoot, config.fev.assetsSubDirectory)
shell.rm('-rf', assetsPath)
shell.mkdir('-p', assetsPath)
shell.config.silent = true
shell.cp('-R', 'static/*', assetsPath)
shell.config.silent = false

webpack(webpackConfig, function (err, stats) {
 spinner.stop()
 if (err) throw err
 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'
 ))
})

webpack.test.conf.js

var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var env = config.fev.env

var webpackConfig = merge(baseWebpackConfig, {
 module: {
  rules: utils.styleLoaders({
   sourceMap: config.fev.productionSourceMap,
   extract: true
  })
 },
 devtool: config.fev.productionSourceMap ? '#source-map' : false,
 output: {
  path: config.fev.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 webpack.optimize.UglifyJsPlugin({
   compress: {
    warnings: false,
    drop_console: true
   },
   
   sourceMap: true
  }),
  // extract css into its own file
  new ExtractTextPlugin({
   filename: utils.assetsPath('css/[name].[contenthash].css')
  }),
  // 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.fev.index,
   template: 'index.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'
  }),
  // split vendor js into its own file
  new webpack.optimize.CommonsChunkPlugin({
   name: 'vendor',
   minChunks: function (module, count) {
    // any required modules inside node_modules are extracted to 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',
   chunks: ['vendor']
  })
 ]
})

if (config.fev.productionGzip) {
 var CompressionWebpackPlugin = require('compression-webpack-plugin')

 webpackConfig.plugins.push(
  new CompressionWebpackPlugin({
   asset: '[path].gz[query]',
   algorithm: 'gzip',
   test: new RegExp(
    '\\.(' +
    config.fev.productionGzipExtensions.join('|') +
    ')$'
   ),
   threshold: 10240,
   minRatio: 0.8
  })
 )
}
if (config.fev.bundleAnalyzerReport) {
 var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
 webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig

3、在config文件中增加环境变量配置

详解Webpack多环境代码打包的方法

test.env.js 增加环境变量

module.exports = {
 NODE_ENV: '"fev"'
}

index.js

// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    // assetsPublicPath: './',
    assetsPublicPath: '',    //公共资源路径
    productionSourceMap: false,
    // 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
  },
  fev: {
    env: require('./test.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: './',  //公共资源路径
    productionSourceMap: false,
    // 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
  },
  test: {
    env: require('./test.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: './',
    productionSourceMap: false,
    // 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
  },
  dev: {
    env: require('./dev.env'),
    port: 8081,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      // '/api':{
      //   target:'http://jsonplaceholder.typicode.com',
      //   changeOrigin:true,
      //   pathRewrite:{
      //     '/api':''
      //   }
      // }
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }
}

4、在main.js文件中在增加环境变量判断

if(process.env.NODE_ENV == 'production'){
  defines.html_url = '正式环境URL';
}
if(process.env.NODE_ENV == 'development'){
defines.html_url = '开发环境URL';
} 
if(process.env.NODE_ENV == 'fev'){ 

defines.html_url = '测试环境URL'; 
}

5、如果公共资源路径,在不同环境中需要更改。在webpack.base.conf.js 中配置打包文件输出的公共路径。

var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
//增加文件路径判断
var webpack_public_path = '';
 if(process.env.NODE_ENV === 'production'){
  webpack_public_path = config.build.assetsPublicPath;
 }else if(process.env.NODE_ENV === 'fev'){
  webpack_public_path = config.fev.assetsPublicPath;
 }else if(process.env.NODE_ENV === 'dev'){
  webpack_public_path = config.dev.assetsPublicPath;
 }
function resolve (dir) {
 return path.join(__dirname, '..', dir)
}
module.exports = {

 //测试使用
 entry: {
  app: ["promise-polyfill", "./src/main.js"]
 },
 // entry: {
 //  app: './src/main.js'
 // },
 output: {
  path: config.build.assetsRoot,
  filename: '[name].js',
  publicPath: webpack_public_path
  // publicPath: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'fev' ? config.build.assetsPublicPath
  //  : config.dev.assetsPublicPath
 },

 resolve: {
  extensions: ['.js', '.vue', '.json'],
  modules: [
   resolve('src'),
   resolve('node_modules'),
  ],
  alias: {
   'vue$': 'vue/dist/vue.common.js',
   'src': resolve('src'),
   'assets': resolve('src/assets'),
   'components': resolve('src/components'),
   'vendor': path.resolve(__dirname, '../src/api'),
   // 'vendor': path.resolve(__dirname, '../src/vendor'),
  }
 },
 module: {
  rules: [
   {
    test: /\.vue$/,
    loader: 'vue-loader'
   },
   {
    test: /\.js$/,
    loader: 'babel-loader',
    include: [resolve('src'), resolve('test')]
   },
   {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    query: {
     limit: 10000,
     name: utils.assetsPath('img/[name].[hash:7].[ext]')
    }
   },
   {
    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
    loader: 'url-loader',
    query: {
     limit: 10000,
     name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
    }
   }
  ]
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
读jQuery之十一 添加事件核心方法
Jul 31 Javascript
JS小功能(setInterval实现图片效果显示时间)实例代码
Nov 28 Javascript
jquery.mobile 共同布局遇到的问题小结
Feb 10 Javascript
BootStrap Table 分页后重新搜索问题的解决办法
Aug 08 Javascript
在线引用最新jquery文件的实现方法
Aug 26 Javascript
微信小程序 数据绑定详解及实例
Oct 25 Javascript
jQuery Password Validation密码验证
Dec 30 Javascript
第一个Vue插件从封装到发布
Nov 22 Javascript
基于JS实现数字动态变化显示效果附源码
Jul 18 Javascript
mpvue实现左侧导航与右侧内容的联动
Oct 21 Javascript
基于JS正则表达式实现模板数据动态渲染(实现思路详解)
Mar 07 Javascript
JavaScript随机数的组合问题案例分析
May 16 Javascript
浅析vue-router jquery和params传参(接收参数)$router $route的区别
Aug 03 #jQuery
浅析Vue 和微信小程序的区别、比较
Aug 03 #Javascript
Vue 项目分环境打包的方法示例
Aug 03 #Javascript
如何在vue里添加好看的lottie动画
Aug 02 #Javascript
原生js实现form表单序列化的方法
Aug 02 #Javascript
详解基于Vue2.0实现的移动端弹窗(Alert, Confirm, Toast)组件
Aug 02 #Javascript
详解vue指令与$nextTick 操作DOM的不同之处
Aug 02 #Javascript
You might like
社区(php&&mysql)四
2006/10/09 PHP
php使用Jpgraph绘制简单X-Y坐标图的方法
2015/06/10 PHP
图文详解PHP环境搭建教程
2016/07/16 PHP
Laravel学习教程之IOC容器的介绍与用例
2017/08/15 PHP
浅析PHP开发规范
2018/02/05 PHP
javascript据option的value值快速设定初始的selected选项
2007/08/13 Javascript
avalonjs制作响应式瀑布流特效
2015/05/06 Javascript
介绍一个简单的JavaScript类框架
2015/06/24 Javascript
JavaScript类继承及实例化的方法
2015/07/25 Javascript
javascript函数式编程程序员的工具集
2015/10/11 Javascript
JS三级可折叠菜单实现方法
2016/02/29 Javascript
解决jQuery ajax动态新增节点无法触发点击事件的问题
2017/05/24 jQuery
老生常谈javascript的面向对象思想
2017/08/22 Javascript
Node.js中sequelize时区的配置方法
2017/12/10 Javascript
解决vue组件没显示,没起作用,没报错,但该显示的组件没显示问题
2020/09/02 Javascript
vue中的循环对象属性和属性值用法
2020/09/04 Javascript
[40:06]DOTA2亚洲邀请赛 4.3 突围赛 Liquid vs VGJ.T 第一场
2018/04/04 DOTA
python中实现定制类的特殊方法总结
2014/09/28 Python
django基础之数据库操作方法(详解)
2017/05/24 Python
如何利用Python分析出微信朋友男女统计图
2019/01/25 Python
python 画二维、三维点之间的线段实现方法
2019/07/07 Python
Django 开发环境配置过程详解
2019/07/18 Python
pycharm配置当鼠标悬停时快速提示方法参数
2019/07/31 Python
pytorch 常用线性函数详解
2020/01/15 Python
在Python中用GDAL实现矢量对栅格的切割实例
2020/03/11 Python
美国女孩洋娃娃店:American Girl
2017/10/24 全球购物
澳大利亚在线购买葡萄酒:The Wine Collective
2020/02/20 全球购物
教育系毕业生中文求职信范文
2013/10/06 职场文书
环境工程大学生个人的自我评价
2013/10/08 职场文书
航空学院求职信
2014/06/11 职场文书
村创先争优活动总结
2014/08/28 职场文书
节水倡议书
2015/01/19 职场文书
寒假致家长的一封信
2015/10/10 职场文书
《角的初步认识》教学反思
2016/02/17 职场文书
如何书写公司员工保密协议?
2019/06/27 职场文书
SQL Server作业失败:无法确定所有者是否有服务器访问权限的解决方法
2021/06/30 SQL Server