当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解Webpack多环境代码打包的方法

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

2019年06月04日  | 移动技术网IT编程  | 我要评论

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

在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文件中添加相应文件

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  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  with correct asset hash for caching.
  // you can customize output by editing /
  // see https://github.com/ampedandwired/html-webpack-plugin
  new htmlwebpackplugin({
   filename: config.fev.index,
   template: '',
   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文件中增加环境变量配置

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/'),
    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/'),
    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/'),
    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]')
    }
   }
  ]
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网