-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathextractLoader.js
227 lines (192 loc) · 7.37 KB
/
extractLoader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import vm from "vm";
import path from "path";
import {getOptions} from "loader-utils";
import resolve from "resolve";
import btoa from "btoa";
import * as babel from "babel-core";
/**
* @typedef {Object} LoaderContext
* @property {function} cacheable
* @property {function} async
* @property {function} addDependency
* @property {function} loadModule
* @property {string} resourcePath
* @property {object} options
*/
/**
* Executes the given module's src in a fake context in order to get the resulting string.
*
* @this LoaderContext
* @param {string} src
* @throws Error
*/
async function extractLoader(src) {
const done = this.async();
const options = getOptions(this) || {};
const publicPath = getPublicPath(options, this);
this.cacheable();
try {
done(null, await evalDependencyGraph({
loaderContext: this,
src,
filename: this.resourcePath,
publicPath,
}));
} catch (error) {
done(error);
}
}
function evalDependencyGraph({loaderContext, src, filename, publicPath = ""}) {
const moduleCache = new Map();
function loadModule(filename) {
return new Promise((resolve, reject) => {
// loaderContext.loadModule automatically calls loaderContext.addDependency for all requested modules
loaderContext.loadModule(filename, (error, src) => {
if (error) {
reject(error);
} else {
resolve(src);
}
});
});
}
function extractExports(exports) {
const hasBtoa = "btoa" in global;
const previousBtoa = global.btoa;
global.btoa = btoa;
try {
return exports.toString();
} catch (error) {
throw error;
} finally {
if (hasBtoa) {
global.btoa = previousBtoa;
} else {
delete global.btoa;
}
}
}
function extractQueryFromPath(givenRelativePath) {
const indexOfLastExclMark = givenRelativePath.lastIndexOf("!");
const indexOfQuery = givenRelativePath.lastIndexOf("?");
if (indexOfQuery !== -1 && indexOfQuery > indexOfLastExclMark) {
return {
relativePathWithoutQuery: givenRelativePath.slice(0, indexOfQuery),
query: givenRelativePath.slice(indexOfQuery),
};
}
return {
relativePathWithoutQuery: givenRelativePath,
query: "",
};
}
async function evalModule(src, filename) {
src = babel.transform(src, {
babelrc: false,
presets: [
[
require("babel-preset-env"), {
modules: "commonjs",
targets: {nodejs: "current"},
},
],
],
plugins: [require("babel-plugin-add-module-exports")],
}).code;
const script = new vm.Script(src, {
filename,
displayErrors: true,
});
const newDependencies = [];
const exports = {};
const sandbox = Object.assign({}, global, {
module: {
exports,
},
exports,
__webpack_public_path__: publicPath, // eslint-disable-line camelcase
require: givenRelativePath => {
const {relativePathWithoutQuery, query} = extractQueryFromPath(givenRelativePath);
const indexOfLastExclMark = relativePathWithoutQuery.lastIndexOf("!");
const loaders = givenRelativePath.slice(0, indexOfLastExclMark + 1);
const relativePath = relativePathWithoutQuery.slice(indexOfLastExclMark + 1);
const absolutePath = resolve.sync(relativePath, {
basedir: path.dirname(filename),
});
const ext = path.extname(absolutePath);
if (moduleCache.has(absolutePath)) {
return moduleCache.get(absolutePath);
}
// If the required file is a js file, we just require it with node's require.
// If the required file should be processed by a loader we do not touch it (even if it is a .js file).
if (loaders === "" && ext === ".js") {
// Mark the file as dependency so webpack's watcher is working for the css-loader helper.
// Other dependencies are automatically added by loadModule() below
loaderContext.addDependency(absolutePath);
const exports = require(absolutePath); // eslint-disable-line import/no-dynamic-require
moduleCache.set(absolutePath, exports);
return exports;
}
const rndPlaceholder = "__EXTRACT_LOADER_PLACEHOLDER__" + rndNumber() + rndNumber();
newDependencies.push({
absolutePath,
absoluteRequest: loaders + absolutePath + query,
rndPlaceholder,
});
return rndPlaceholder;
},
});
script.runInNewContext(sandbox);
const extractedDependencyContent = await Promise.all(
newDependencies.map(async ({absolutePath, absoluteRequest}) => {
const src = await loadModule(absoluteRequest);
return evalModule(src, absolutePath);
})
);
const contentWithPlaceholders = extractExports(sandbox.module.exports);
const extractedContent = extractedDependencyContent.reduce((content, dependencyContent, idx) => {
const pattern = new RegExp(newDependencies[idx].rndPlaceholder, "g");
return content.replace(pattern, dependencyContent);
}, contentWithPlaceholders);
moduleCache.set(filename, extractedContent);
return extractedContent;
}
return evalModule(src, filename);
}
/**
* @returns {string}
*/
function rndNumber() {
return Math.random()
.toString()
.slice(2);
}
// getPublicPath() encapsulates the complexity of reading the publicPath from the current
// webpack config. Let's keep the complexity in this function.
/* eslint-disable complexity */
/**
* Retrieves the public path from the loader options, context.options (webpack <4) or context._compilation (webpack 4+).
* context._compilation is likely to get removed in a future release, so this whole function should be removed then.
* See: https://github.com/peerigon/extract-loader/issues/35
*
* @deprecated
* @param {Object} options - Extract-loader options
* @param {Object} context - Webpack loader context
* @returns {string}
*/
function getPublicPath(options, context) {
if ("publicPath" in options) {
return typeof options.publicPath === "function" ? options.publicPath(context) : options.publicPath;
}
if (context.options && context.options.output && "publicPath" in context.options.output) {
return context.options.output.publicPath;
}
if (context._compilation && context._compilation.outputOptions && "publicPath" in context._compilation.outputOptions) {
return context._compilation.outputOptions.publicPath;
}
return "";
}
/* eslint-enable complexity */
// For CommonJS interoperability
module.exports = extractLoader;
export default extractLoader;