UNPKG

3.25 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 (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 // stats.compilation.outputOptions.path,
57
58 fs.ensureFileSync(filepathname)
59
60 // for (let key in stats.compilation) {
61 // console.log(key)
62 // }
63
64 // 生成入口对照表
65 if (stats.compilation.entrypoints) {
66 stats.compilation.entrypoints.forEach((value, key) => {
67 // console.log(value, key, map)
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}