UNPKG

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