1 | const fs = require('fs-extra')
|
2 | const path = require('path')
|
3 |
|
4 | const generateFilemap = require('./generate-filemap-from-compilation')
|
5 | const getChunkmapPath = require('./get-chunkmap-path')
|
6 | const getDistPath = require('./get-dist-path')
|
7 |
|
8 | const times = n => f => {
|
9 | let iter = i => {
|
10 | if (i === n) return
|
11 | f(i)
|
12 | iter(i + 1)
|
13 | }
|
14 | return iter(0)
|
15 | }
|
16 |
|
17 | const isNotSourcemap = (filename) => (
|
18 | !/\.(js|css)\.map$/i.test(filename)
|
19 | )
|
20 |
|
21 | const getFilePathname = (dirname, file) => {
|
22 | if (process.env.WEBPACK_BUILD_ENV === 'dev') return file
|
23 | return `${dirname}/${file}`
|
24 | }
|
25 |
|
26 | const log = (obj, spaceCount = 1, deep = 2) => {
|
27 | if (typeof obj === 'object') {
|
28 | let spaces = ''
|
29 | times(spaceCount)(() => {
|
30 | spaces += ' '
|
31 | })
|
32 | for (let key in obj) {
|
33 | console.log(spaces + key)
|
34 | if (spaceCount < deep)
|
35 | log(obj[key], spaceCount + 1, deep)
|
36 | }
|
37 | }
|
38 | }
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | module.exports = async (stats, localeId) => {
|
47 | const chunkmap = {}
|
48 | const entryChunks = {}
|
49 |
|
50 | const dirRelative = path.relative(getDistPath(), stats.compilation.outputOptions.path).replace(`\\`, '/')
|
51 | const filepathname = getChunkmapPath()
|
52 |
|
53 |
|
54 | fs.ensureFileSync(filepathname)
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 | if (stats.compilation.entrypoints) {
|
62 | stats.compilation.entrypoints.forEach((value, key) => {
|
63 |
|
64 | entryChunks[key] = []
|
65 | value.chunks.forEach(chunk => {
|
66 | if (Array.isArray(chunk.files))
|
67 | chunk.files
|
68 | .filter(file => isNotSourcemap(file))
|
69 | .forEach(file =>
|
70 | entryChunks[key].push(getFilePathname(dirRelative, file))
|
71 | )
|
72 | })
|
73 | })
|
74 | chunkmap['.entrypoints'] = entryChunks
|
75 | }
|
76 |
|
77 |
|
78 | chunkmap['.files'] = generateFilemap(stats, dirRelative)
|
79 |
|
80 |
|
81 | for (let id in stats.compilation.chunks) {
|
82 | const o = stats.compilation.chunks[id]
|
83 | if (typeof o.name === 'undefined' || o.name === null) continue
|
84 | chunkmap[o.name] = o.files
|
85 |
|
86 | if (Array.isArray(o.files))
|
87 | chunkmap[o.name] = o.files
|
88 | .filter(filename => isNotSourcemap(filename))
|
89 | .map(filename => getFilePathname(dirRelative, filename))
|
90 | }
|
91 |
|
92 | let json = {}
|
93 |
|
94 | if (localeId) {
|
95 | json = fs.readJsonSync(filepathname)
|
96 | json[`.${localeId}`] = chunkmap
|
97 | } else {
|
98 | json = chunkmap
|
99 | }
|
100 |
|
101 | await fs.writeJsonSync(
|
102 | filepathname,
|
103 | json,
|
104 | {
|
105 | spaces: 4
|
106 | }
|
107 | )
|
108 |
|
109 | return json
|
110 | }
|