|
1 | | -export default class PagesPlugin { |
| 1 | +import { ConcatSource } from 'webpack-sources' |
| 2 | + |
| 3 | +const isImportChunk = /^chunks[/\\].*\.js$/ |
| 4 | +const matchChunkName = /^chunks[/\\](.*)$/ |
| 5 | + |
| 6 | +class DynamicChunkTemplatePlugin { |
| 7 | + apply (chunkTemplate) { |
| 8 | + chunkTemplate.plugin('render', function (modules, chunk) { |
| 9 | + if (!isImportChunk.test(chunk.name)) { |
| 10 | + return modules |
| 11 | + } |
| 12 | + |
| 13 | + const chunkName = matchChunkName.exec(chunk.name)[1] |
| 14 | + const source = new ConcatSource() |
| 15 | + |
| 16 | + source.add(` |
| 17 | + __NEXT_REGISTER_CHUNK('${chunkName}', function() { |
| 18 | + `) |
| 19 | + source.add(modules) |
| 20 | + source.add(` |
| 21 | + }) |
| 22 | + `) |
| 23 | + |
| 24 | + return source |
| 25 | + }) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +export default class DynamicChunksPlugin { |
2 | 30 | apply (compiler) { |
3 | | - const isImportChunk = /^chunks[/\\].*\.js$/ |
4 | | - const matchChunkName = /^chunks[/\\](.*)$/ |
5 | | - |
6 | | - compiler.plugin('after-compile', (compilation, callback) => { |
7 | | - const chunks = Object |
8 | | - .keys(compilation.namedChunks) |
9 | | - .map(key => compilation.namedChunks[key]) |
10 | | - .filter(chunk => isImportChunk.test(chunk.name)) |
11 | | - |
12 | | - chunks.forEach((chunk) => { |
13 | | - const asset = compilation.assets[chunk.name] |
14 | | - if (!asset) return |
15 | | - |
16 | | - const chunkName = matchChunkName.exec(chunk.name)[1] |
17 | | - |
18 | | - const content = asset.source() |
19 | | - const newContent = ` |
20 | | - window.__NEXT_REGISTER_CHUNK('${chunkName}', function() { |
21 | | - ${content} |
22 | | - }) |
23 | | - ` |
24 | | - // Replace the exisiting chunk with the new content |
25 | | - compilation.assets[chunk.name] = { |
26 | | - source: () => newContent, |
27 | | - size: () => newContent.length |
28 | | - } |
29 | | - |
30 | | - // This is to support, webpack dynamic import support with HMR |
31 | | - compilation.assets[`chunks/${chunk.id}`] = { |
32 | | - source: () => newContent, |
33 | | - size: () => newContent.length |
34 | | - } |
| 31 | + compiler.plugin('compilation', (compilation) => { |
| 32 | + compilation.chunkTemplate.apply(new DynamicChunkTemplatePlugin()) |
| 33 | + |
| 34 | + compilation.plugin('additional-chunk-assets', (chunks) => { |
| 35 | + chunks = chunks.filter(chunk => |
| 36 | + isImportChunk.test(chunk.name) && compilation.assets[chunk.name] |
| 37 | + ) |
| 38 | + |
| 39 | + chunks.forEach((chunk) => { |
| 40 | + // This is to support, webpack dynamic import support with HMR |
| 41 | + const copyFilename = `chunks/${chunk.name}` |
| 42 | + compilation.additionalChunkAssets.push(copyFilename) |
| 43 | + compilation.assets[copyFilename] = compilation.assets[chunk.name] |
| 44 | + }) |
35 | 45 | }) |
36 | | - callback() |
37 | 46 | }) |
38 | 47 | } |
39 | 48 | } |
0 commit comments