From a7ce7392ecbc0c54415f2abb89785ab9c1b1d600 Mon Sep 17 00:00:00 2001 From: Michell Ocana do Espirito Santo Date: Tue, 19 Mar 2019 09:01:53 -0300 Subject: [PATCH 1/2] Adding "searchByChunkId" option --- index.js | 13 ++++++++++--- test/spec.js | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index fbdd58e..b2f39b7 100644 --- a/index.js +++ b/index.js @@ -79,6 +79,7 @@ const defaultOptions = { include: 'asyncChunks', fileBlacklist: [/\.map/], excludeHtmlNames: [], + searchByChunkId: false }; class PreloadPlugin { @@ -161,11 +162,17 @@ class PreloadPlugin { extractedChunks = compilation.chunks .filter((chunk) => { const chunkName = chunk.name; - // Works only for named chunks - if (!chunkName) { + const chunkId = chunk.id; + + // Works only for named chunks, or chunks with id when "searchByChunkId" option is enabled + if (!chunkName && !options.searchByChunkId) { return false; } - return options.include.indexOf(chunkName) > -1; + + return ( + (options.include.indexOf(chunkName) > -1) || + (options.searchByChunkId && options.include.indexOf(chunkId) > -1) + ); }); } diff --git a/test/spec.js b/test/spec.js index bc4ee29..e95fc59 100644 --- a/test/spec.js +++ b/test/spec.js @@ -373,6 +373,46 @@ describe('PreloadPlugin filters chunks', function() { }); compiler.outputFileSystem = new MemoryFileSystem(); }); + + it('based on chunkid', (done) => { + const compiler = webpack({ + entry: path.join(__dirname, 'fixtures', 'file.js'), + output: { + path: OUTPUT_DIR, + filename: 'bundle.js', + publicPath: '/', + }, + plugins: [ + new HtmlWebpackPlugin(), + + // Setting home chunk id to "homeChunk" + new webpack.NamedChunksPlugin(chunk => { + const chunkName = chunk.name; + + if (chunkName) { + if (chunkName === 'home') { + return 'homeChunk'; + } + + return chunk.name; + } + }), + + // Preloading home chunk and searching by it chunk id + new PreloadPlugin({ + include: ['homeChunk'], + searchByChunkId: true + }) + ], + }, function(err, result) { + expect(err).toBeFalsy(); + expect(JSON.stringify(result.compilation.errors)).toBe('[]'); + const html = result.compilation.assets['index.html'].source(); + expect(html).toContain(' ``` +If you are using webpack's `NamedChunksPlugin` (or `NamedChunkIdsPlugin` if using webpack 5) you can also tell the plugin to search by the chunk id using the `searchByChunkId` option: +```js +plugins: [ + new HtmlWebpackPlugin(), + new PreloadWebpackPlugin({ + rel: 'preload', + include: ['home'], + searchByChunkId: true + }) +] +``` + It is very common in Webpack to use loaders such as `file-loader` to generate assets for specific types, such as fonts or images. If you wish to preload these files as well, you can use `include` with value `allAssets`: