Skip to content
This repository was archived by the owner on Jan 21, 2021. It is now read-only.

Commit edb0cc8

Browse files
committed
add feature to potentially provide more types
1 parent cfe5ac1 commit edb0cc8

3 files changed

Lines changed: 51 additions & 0 deletions

File tree

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,24 @@ plugins: [
8888
]
8989
```
9090

91+
In case you need more fine control of the `as` atribute, you could also provide a function here.
92+
When using it, entry name will be provided as the parameter, and function itself should return a
93+
string for `as` attribute:
94+
95+
```javascript
96+
plugins: [
97+
new HtmlWebpackPlugin(),
98+
new PreloadWebpackPlugin({
99+
rel: 'preload',
100+
as(entry) {
101+
if (/\.css$/.test(entry)) return 'style';
102+
if (/\.png$/.test(entry)) return 'image';
103+
return 'script';
104+
}
105+
})
106+
]
107+
```
108+
91109
By default, the plugin will assume async script chunks will be preloaded. This is the equivalent of:
92110

93111
```js

index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ class PreloadPlugin {
7676
let asValue;
7777
if (!options.as) {
7878
asValue = entry.match(/\.css$/) ? 'style' : 'script';
79+
} else if (typeof options.as === 'function') {
80+
asValue = options.as(entry);
7981
} else {
8082
asValue = options.as;
8183
}

test/spec.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,37 @@ describe('PreloadPlugin preloads normal chunks', function() {
190190
});
191191
compiler.outputFileSystem = new MemoryFileSystem();
192192
});
193+
194+
it('use custom as attribute based on return value of callback', (done) => {
195+
const compiler = webpack({
196+
entry: path.join(__dirname, 'fixtures', 'file.js'),
197+
output: {
198+
path: OUTPUT_DIR,
199+
filename: 'bundle.js',
200+
chunkFilename: 'chunk.[chunkhash].css',
201+
publicPath: '/',
202+
},
203+
plugins: [
204+
new HtmlWebpackPlugin(),
205+
new PreloadPlugin({
206+
rel: 'preload',
207+
as(entry) {
208+
if (entry.indexOf('/chunk') === 0) return 'style';
209+
return 'script';
210+
},
211+
include: 'all',
212+
}),
213+
],
214+
}, function(err, result) {
215+
expect(err).toBeFalsy();
216+
expect(JSON.stringify(result.compilation.errors)).toBe('[]');
217+
const html = result.compilation.assets['index.html'].source();
218+
expect(html).toContain('<link rel="preload" as="style" href="/chunk');
219+
expect(html).toContain('<link rel="preload" as="script" href="/bundle.js"');
220+
done();
221+
});
222+
compiler.outputFileSystem = new MemoryFileSystem();
223+
});
193224
});
194225

195226
describe('PreloadPlugin prefetches normal chunks', function() {

0 commit comments

Comments
 (0)