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 |
|
20 |
|
21 | const readClientFile = (
|
22 | filename,
|
23 | localeId,
|
24 | compilation,
|
25 | isPathname = false
|
26 | ) => {
|
27 |
|
28 | if (filename === true)
|
29 | return readClientFile(
|
30 | localeId,
|
31 | compilation || undefined,
|
32 | isPathname || undefined,
|
33 | true
|
34 | );
|
35 |
|
36 |
|
37 | if (typeof compilation === 'object') {
|
38 | const filemap = generateFilemap(compilation);
|
39 | if (typeof filemap === 'object') {
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 | if (
|
48 | typeof filemap[filename] === 'string' &&
|
49 | typeof compilation.assets[filemap[filename]] !== 'undefined'
|
50 | ) {
|
51 | const asset = compilation.assets[filemap[filename]];
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 | if (typeof asset.source === 'function') return asset.source();
|
58 | if (typeof asset._value !== 'undefined') return asset._value;
|
59 | if (typeof asset._cachedSource !== 'undefined')
|
60 | return asset._cachedSource;
|
61 |
|
62 | }
|
63 | }
|
64 | }
|
65 |
|
66 |
|
67 | let pathnames = getFilePath(filename, localeId, isPathname);
|
68 | if (!Array.isArray(pathnames)) pathnames = [pathnames];
|
69 |
|
70 | const results = pathnames.map(pathname => {
|
71 | if (isUrl(pathname)) {
|
72 | if (__DEV__) {
|
73 | const syncRequest = require('sync-request');
|
74 |
|
75 | return syncRequest('GET', pathname, {}).getBody();
|
76 | } else {
|
77 | return `<!-- The pathname for file '${filename}' is a URL. Rendering file content from URL can only be done in DEV mode. -->`;
|
78 | }
|
79 | }
|
80 |
|
81 | if (
|
82 | process.env.WEBPACK_BUILD_TYPE === 'spa' &&
|
83 | process.env.WEBPACK_BUILD_ENV === 'dev'
|
84 | ) {
|
85 | return `<!-- http://localhost:${getPort()}${pathname} -->`;
|
86 |
|
87 |
|
88 | }
|
89 |
|
90 | return fs.readFileSync(
|
91 | path.resolve(
|
92 | getDirDistPublic(getDistPath()),
|
93 | pathname.replace(/^\//, '')
|
94 | ),
|
95 | 'utf-8'
|
96 | );
|
97 | });
|
98 |
|
99 | return results.join('\n\n');
|
100 | };
|
101 |
|
102 | module.exports = readClientFile;
|