|
| 1 | +/** @type {import("../../../../").LoaderDefinitionFunction} */ |
| 2 | +module.exports = async function loader() { |
| 3 | + const callback = this.async(); |
| 4 | + const loader = this; |
| 5 | + const compilerName = `extract:${loader.resourcePath}`; |
| 6 | + const compiler = loader._compiler; |
| 7 | + const filename = "*"; |
| 8 | + const childCompiler = loader._compilation.createChildCompiler( |
| 9 | + compilerName, |
| 10 | + { |
| 11 | + filename, |
| 12 | + }, |
| 13 | + [] |
| 14 | + ); |
| 15 | + |
| 16 | + const NodeTemplatePlugin = compiler.webpack.node.NodeTemplatePlugin; |
| 17 | + new NodeTemplatePlugin().apply(childCompiler); |
| 18 | + |
| 19 | + const NodeTargetPlugin = compiler.webpack.node.NodeTargetPlugin; |
| 20 | + new NodeTargetPlugin().apply(childCompiler); |
| 21 | + |
| 22 | + const { |
| 23 | + EntryOptionPlugin, |
| 24 | + library: { |
| 25 | + EnableLibraryPlugin |
| 26 | + } |
| 27 | + } = loader._compiler.webpack; |
| 28 | + |
| 29 | + new EnableLibraryPlugin('commonjs2').apply(childCompiler); |
| 30 | + |
| 31 | + EntryOptionPlugin.applyEntryOption(childCompiler, loader.context, { |
| 32 | + child: { |
| 33 | + library: { |
| 34 | + type: 'commonjs2' |
| 35 | + }, |
| 36 | + import: [`!!${loader.resourcePath}`] |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + const LimitChunkCountPlugin = compiler.webpack.optimize.LimitChunkCountPlugin; |
| 41 | + |
| 42 | + new LimitChunkCountPlugin({ |
| 43 | + maxChunks: 1 |
| 44 | + }).apply(childCompiler); |
| 45 | + |
| 46 | + let source; |
| 47 | + |
| 48 | + childCompiler.hooks.compilation.tap(compilerName, compilation => { |
| 49 | + compilation.hooks.processAssets.tap(compilerName, () => { |
| 50 | + source = compilation.assets[filename] && compilation.assets[filename].source(); |
| 51 | + |
| 52 | + // Remove all chunk assets |
| 53 | + compilation.chunks.forEach(chunk => { |
| 54 | + chunk.files.forEach(file => { |
| 55 | + compilation.deleteAsset(file); |
| 56 | + }); |
| 57 | + }); |
| 58 | + }); |
| 59 | + }); |
| 60 | + |
| 61 | + try { |
| 62 | + await new Promise((resolve, reject) => { |
| 63 | + childCompiler.runAsChild((err, _entries, compilation) => { |
| 64 | + if (err) { |
| 65 | + return reject(err); |
| 66 | + } |
| 67 | + |
| 68 | + if (compilation.errors.length > 0) { |
| 69 | + return reject(compilation.errors[0]); |
| 70 | + } |
| 71 | + |
| 72 | + resolve(); |
| 73 | + }); |
| 74 | + }) |
| 75 | + } catch (e) { |
| 76 | + callback(e); |
| 77 | + return; |
| 78 | + } |
| 79 | + |
| 80 | + if (!source) { |
| 81 | + callback(new Error("Didn't get a result from child compiler")); |
| 82 | + return; |
| 83 | + } |
| 84 | + |
| 85 | + callback(null, source); |
| 86 | +} |
0 commit comments