diff --git a/README.md b/README.md
index c9831cc..e7f5985 100644
--- a/README.md
+++ b/README.md
@@ -161,6 +161,18 @@ will inject just this:
```
+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`:
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('