UNPKG

2.75 kBJavaScriptView Raw
1const fs = require('fs-extra')
2const path = require('path')
3const isUrl = require('is-url')
4
5const getFilePath = require('./get-client-file-path')
6const generateFilemap = require('./generate-filemap-from-compilation')
7const getDistPath = require('./get-dist-path')
8
9/**
10 * 读取目标客户端打包结果文件的内容
11 * @param {String} filename 要查找的文件的文件名。根据打包文件对应表 (chunkmap) 查询文件名和实际打包结果文件的对应关系
12 * @param {String} [localeId] 当前语言
13 * @param {Object} [compilation] Webpack compilation 对象
14 * @param {Boolean} [isPathname=false] 如果标记为 true,表示提供的 filename 为确切的访问地址,无需查询对照表,直接返回结果
15 * @returns {String} 文件内容
16 */
17const readClientFile = (filename, localeId, compilation, isPathname = false) => {
18 // 如果第一个参数为 true,表示标记为 pathname
19 if (filename === true) return readClientFile(localeId, compilation || undefined, isPathname || undefined, true)
20
21 // 如果提供了 webpack compilation 数据,直接从其中查询对应文件的最终内容并返回
22 if (typeof compilation === 'object') {
23 const filemap = generateFilemap(compilation)
24 if (typeof filemap === 'object') {
25 // for (let key in compilation) {
26 // console.log(key)
27 // }
28
29 if (typeof filemap[filename] === 'string' &&
30 typeof compilation.assets[filemap[filename]] !== 'undefined'
31 ) {
32 const obj = compilation.assets[filemap[filename]]
33 // console.log(filename, filemap[filename])
34 // if (!obj._value) {
35 // console.log(obj)
36 // }
37 if (typeof obj._value !== 'undefined') return obj._value
38 if (typeof obj._cachedSource !== 'undefined') return obj._cachedSource
39 // return '123'
40 }
41 }
42 }
43
44 const pathname = getFilePath(filename, localeId, isPathname)
45 if (isUrl(pathname)) {
46 if (__DEV__) {
47 const syncRequest = require('sync-request')
48 // console.log(`${pathname} is URL`)
49 return syncRequest('GET', pathname, {}).getBody()
50 } else {
51 return `<!-- The pathname for file '${filename}' is a URL. Rendering file content from URL can only be done in DEV mode. -->`
52 }
53 }
54
55 return fs.readFileSync(
56 path.resolve(
57 getDistPath(),
58 'public/',
59 getFilePath(filename, localeId, isPathname).replace(/^\//, '')
60 ),
61 'utf-8'
62 )
63}
64
65module.exports = readClientFile