【问题标题】:Webpack different names for entriesWebpack 条目的不同名称
【发布时间】:2017-08-28 04:04:37
【问题描述】:

如何为不同的输入输出指定不同的filename

例如:

module.exports = {
  context: path.resolve(__dirname, 'assets'),
  entry: {
    vendor: ['react', 'react-dom', 'lodash', 'redux'],
    app: './src/app.js'
  }
  output: {
    path: path.resolve(__dirname, (isDevelopment) ? 'demo' : 'build'),
    filename: (isDevelopment) ? '[name].js' : '[name][chunkhash:12].js'
  }
}

接收这样的输出

build
-- index.html
-- app.2394035ufas0ue34.js
-- vendor.js

因此浏览器将缓存vendor.js 与所有库。因为我不打算很快和经常迁移到任何主要的新版本。 并且仍然能够在每次需要更新时打破 app.js 的缓存。

是否有某种选项可以将output 设置为

output: {
  app: {
    ...
  },
  vendor: {
    ...
  },
}

【问题讨论】:

    标签: javascript webpack frontend


    【解决方案1】:

    这是工作代码:

      entry: {
        './build/app': './src/app.js',
        './build/vendor': VENDOR_LIBS // or path to your vendor.js
      },
      output: {
        path: __dirname,
        filename: '[name].[chunkhash].js'
      },
    

    将此代码添加到您的 webpack plugins 数组中,作为数组的最后一个元素。

    plugins: [
     ... // place our new plugin here
    ]
    
    function() {
      this.plugin("done", function(stats) {
        const buildDir = __dirname + '/build/';
        const fs = require('fs');
        var vendorTempFileName = '';
    
        new Promise(function(resolve, reject) {
    
          fs.readdir(buildDir, (err, files) => {
            files.forEach(file => {
    
            if (file.substr(0,6) === 'vendor') {
              resolve(file);
            }
    
            });
          });
        }).then(function(file) {
    
          fs.rename( buildDir + file, buildDir + 'vendor.js', function(err) {
            if ( err ) console.log('ERROR: ' + err);
          });
    
        });
    
      });
    }
    

    输出应该如下:

    由于浏览器缓存的原因,不使用块状散列的文件被认为是不好的做法。

    【讨论】:

    • 这仍然没有解决我的不同命名问题。我需要将vendor.js 设置为[name].jsapp.js 设置为[name].[chunkhash].js
    • 我刚刚更新了我的答案。应该可以按你的意愿工作,我测试过了。
    【解决方案2】:

    对于 Webpack 4,我添加了一个快速又脏的 done 挂钩来重命名我的服务工作者脚本:

      // Plugin to rename sw-[chunkhash].js back to sw.js
      class SwNamePlugin {
        apply(compiler) {
          compiler.hooks.done.tap("SW Name Plugin", (stats) => {
            const swChunk = stats.compilation.chunks.find((c) => c.name === "sw");
            fs.rename(path.resolve(outDir, swChunk.files[0]), `${outDir}/sw.js`);
          });
        }
      }
      plugins.push(new SwNamePlugin());
    

    这消除了警告DeprecationWarning: Tapable.plugin is deprecated. Use new API on .hooks instead,您会在 loelsonk 的回答之后看到。

    【讨论】:

      猜你喜欢
      • 2021-01-05
      • 2016-12-17
      • 2015-07-07
      • 2012-10-26
      • 1970-01-01
      • 2023-01-08
      • 2015-04-10
      • 1970-01-01
      • 2019-06-18
      相关资源
      最近更新 更多