1 | const fs = require('fs-extra')
|
2 | const path = require('path')
|
3 | const isUrl = require('is-url')
|
4 |
|
5 | const getFilePath = require('./get-client-file-path')
|
6 | const generateFilemap = require('./generate-filemap-from-compilation')
|
7 | const getDistPath = require('./get-dist-path')
|
8 | const getPort = require('./get-port')
|
9 | const getDirDistPublic = require('../libs/get-dir-dist-public')
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | const readClientFile = (filename, localeId, compilation, isPathname = false) => {
|
20 |
|
21 | if (filename === true) return readClientFile(localeId, compilation || undefined, isPathname || undefined, true)
|
22 |
|
23 |
|
24 | if (typeof compilation === 'object') {
|
25 | const filemap = generateFilemap(compilation)
|
26 | if (typeof filemap === 'object') {
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | if (typeof filemap[filename] === 'string' &&
|
35 | typeof compilation.assets[filemap[filename]] !== 'undefined'
|
36 | ) {
|
37 | const asset = compilation.assets[filemap[filename]]
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
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 |
|
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 |
|
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 |
|
65 |
|
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 |
|
77 | module.exports = readClientFile
|