UNPKG

3.14 kBJavaScriptView Raw
1const fs = require('fs-extra')
2const path = require('path')
3
4const generateFilemap = require('./generate-filemap-from-compilation')
5const getChunkmapPath = require('./get-chunkmap-path')
6const getDistPath = require('./get-dist-path')
7
8const 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
17const isNotSourcemap = (filename) => (
18 !/\.(js|css)\.map$/i.test(filename)
19)
20
21const getFilePathname = (dirname, file) => {
22 if (process.env.WEBPACK_BUILD_ENV === 'dev') return file
23 return `${dirname}/${file}`
24}
25
26const 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 * 写入打包文件对应表 (chunkmap)
42 * @param {*} stats
43 * @param {*} localeId
44 * @returns {Object} 打包文件对应表 (chunkmap)
45 */
46module.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 // stats.compilation.outputOptions.path,
53
54 fs.ensureFileSync(filepathname)
55
56 // for (let key in stats.compilation) {
57 // console.log(key)
58 // }
59
60 // 生成入口对照表
61 if (stats.compilation.entrypoints) {
62 stats.compilation.entrypoints.forEach((value, key) => {
63 // console.log(value, key, map)
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}