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 (compilation, localeId) => {
|
47 | if (typeof compilation !== 'object') return {}
|
48 |
|
49 | const stats = compilation.getStats()
|
50 |
|
51 | const chunkmap = {}
|
52 | const entryChunks = {}
|
53 |
|
54 | const dirRelative = path.relative(getDistPath(), stats.compilation.outputOptions.path).replace(`\\`, '/')
|
55 | const filepathname = getChunkmapPath()
|
56 |
|
57 |
|
58 | fs.ensureFileSync(filepathname)
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 | if (stats.compilation.entrypoints) {
|
66 | stats.compilation.entrypoints.forEach((value, key) => {
|
67 |
|
68 | entryChunks[key] = []
|
69 | value.chunks.forEach(chunk => {
|
70 | if (Array.isArray(chunk.files))
|
71 | chunk.files
|
72 | .filter(file => isNotSourcemap(file))
|
73 | .forEach(file =>
|
74 | entryChunks[key].push(getFilePathname(dirRelative, file))
|
75 | )
|
76 | })
|
77 | })
|
78 | chunkmap['.entrypoints'] = entryChunks
|
79 | }
|
80 |
|
81 |
|
82 | chunkmap['.files'] = generateFilemap(compilation, dirRelative)
|
83 |
|
84 |
|
85 | for (let id in stats.compilation.chunks) {
|
86 | const o = stats.compilation.chunks[id]
|
87 | if (typeof o.name === 'undefined' || o.name === null) continue
|
88 | chunkmap[o.name] = o.files
|
89 |
|
90 | if (Array.isArray(o.files))
|
91 | chunkmap[o.name] = o.files
|
92 | .filter(filename => isNotSourcemap(filename))
|
93 | .map(filename => getFilePathname(dirRelative, filename))
|
94 | }
|
95 |
|
96 | let json = {}
|
97 |
|
98 | if (localeId) {
|
99 | json = fs.readJsonSync(filepathname)
|
100 | json[`.${localeId}`] = chunkmap
|
101 | } else {
|
102 | json = chunkmap
|
103 | }
|
104 |
|
105 | await fs.writeJsonSync(
|
106 | filepathname,
|
107 | json,
|
108 | {
|
109 | spaces: 4
|
110 | }
|
111 | )
|
112 |
|
113 | return json
|
114 | }
|