|
| 1 | +const path = require('path'); |
| 2 | +const relative = require('relative'); |
| 3 | + |
1 | 4 | function MpvuePlugin() {} |
2 | 5 |
|
3 | 6 | MpvuePlugin.prototype.apply = function(compiler) { |
4 | | - const {options: {entry, plugins}} = compiler; |
5 | 7 | compiler.plugin('emit', function(compilation, callback) { |
6 | | - let commonsChunkNames = []; |
7 | | - // 获取所有的 chunk name |
8 | | - plugins.forEach(item => { |
9 | | - let { chunkNames } = item; |
10 | | - if (item.constructor.name === 'CommonsChunkPlugin' && chunkNames) { |
11 | | - commonsChunkNames = commonsChunkNames.concat(chunkNames); |
12 | | - } |
13 | | - }) |
14 | | - let pages = Object.keys(entry); |
15 | | - compilation.chunks.forEach(commonChunk => { |
16 | | - const { files, chunks: childChunks, name } = commonChunk; |
17 | | - let commonWxssFile = files.find(item => item.endsWith('.wxss')); |
18 | | - |
19 | | - if (commonsChunkNames.indexOf(name) > -1 && commonWxssFile) { |
20 | | - childChunks.forEach(item => { |
21 | | - let wxssFile = item.files.find(item => item.endsWith('.wxss')); |
22 | | - if (item.name === 'app' && wxssFile) { // 过滤 app |
23 | | - return; |
24 | | - } |
25 | | - try { |
26 | | - if (compilation.assets[wxssFile]) { |
27 | | - let wxss = compilation.assets[wxssFile].source(); |
28 | | - wxss = `@import "/${commonWxssFile}";\n${wxss}`; |
29 | | - compilation.assets[wxssFile].source = () => wxss; |
| 8 | + Object.keys(compilation.entrypoints).forEach(key => { |
| 9 | + const entry = compilation.entrypoints[key]; |
| 10 | + const { chunks } = entry; |
| 11 | + const entryChunk = chunks.pop(); |
| 12 | + entryChunk.files.forEach(filePath => { |
| 13 | + const extname = path.extname(filePath); |
| 14 | + let content = compilation.assets[filePath].source(); |
| 15 | + chunks.reverse().forEach(chunk => { |
| 16 | + chunk.files.forEach(childFile => { |
| 17 | + if (path.extname(childFile) === extname && compilation.assets[filePath]) { |
| 18 | + content = extname === '.wxss' ? |
| 19 | + `@import "${relative(filePath, childFile)}";\n${content}` |
| 20 | + : `require("${relative(filePath, childFile)}");\n${content}`; |
30 | 21 | } |
31 | | - } catch (error) { |
32 | | - console.error(error, wxssFile) |
33 | | - } |
| 22 | + }) |
| 23 | + compilation.assets[filePath].source = () => content; |
34 | 24 | }) |
35 | | - } |
36 | | - }); |
| 25 | + }) |
| 26 | + }) |
37 | 27 | callback(); |
38 | 28 | }); |
39 | 29 | }; |
|
0 commit comments