Vue CLIでの環境変数管理とビルド最適化の実践

環境モードと変数のカスタマイズ

Vue CLIのビルドプロセスにおいて、コマンドライン引数--modeを使用して環境モードを指定できます。開発環境向けビルドを実行する例:

"scripts": {
  "build:dev": "vue-cli-service build --mode development"
}

webpack構成の高度な設定

vue.config.jsで行う主要な設定:

  • 出力ディレクトリの環境変数指定
  • バンドル分割戦略の定義
  • 画像・JS/CSSの圧縮処理
  • ビルド成果物のアーカイブ

基本設定構成

const path = require('path');
const CompressionPlugin = require('compression-webpack-plugin');
const FileManagerPlugin = require('filemanager-webpack-plugin');

process.env.VUE_APP_VERSION = require('./package.json').version;

function getPath(dir) {
  return path.join(__dirname, dir);
}

module.exports = {
  outputDir: process.env.VUE_APP_OUTPUT_DIR,
  devServer: {
    host: '0.0.0.0',
    port: 9111
  },
  productionSourceMap: false
};

バンドル最適化設定

configureWebpack: config => {
  config.optimization.splitChunks = {
    cacheGroups: {
      thirdParty: {
        name: 'vendor-bundle',
        test: /[\\/]node_modules[\\/]/,
        priority: -10,
        chunks: 'initial'
      },
      coreLibs: {
        name: 'core-deps',
        test: /[\\/]node_modules[\\/](vue|vuex|vue-router)/,
        priority: -5,
        chunks: 'initial'
      },
      commonComponents: {
        name: 'shared-components',
        minChunks: 2,
        priority: -20,
        chunks: 'initial',
        reuseExistingChunk: true
      }
    }
  };
}

圧縮処理の設定

chainWebpack: config => {
  // 画像圧縮設定
  config.module.rule('images')
    .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
    .use('image-webpack-loader')
    .loader('image-webpack-loader')
    .options({ bypassOnDebug: true });

  // 本番環境設定
  if (process.env.NODE_ENV === 'production') {
    config.plugin('compress-assets')
      .use(new CompressionPlugin({
        test: /\.js$|\.css$/,
        threshold: 10240,
        deleteOriginalAssets: false
      }));
    
    config.plugin('archive-builder')
      .use(new FileManagerPlugin({
        onEnd: {
          delete: [`./dist/dist_v${process.env.VUE_APP_VERSION}.zip`],
          archive: [{
            source: './dist',
            destination: `./dist/dist_v${process.env.VUE_APP_VERSION}.zip`
          }]
        }
      }));
  }
}

タグ: vue-cli webpack environment-variables build-optimization compression-plugin

5月15日 22:02 投稿