UNPKG

11 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.pitch = pitch;
7exports.default = _default;
8
9var _path = _interopRequireDefault(require("path"));
10
11var _utils = require("./utils");
12
13var _loaderOptions = _interopRequireDefault(require("./loader-options.json"));
14
15var _index = _interopRequireWildcard(require("./index"));
16
17function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
18
19function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
20
21function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
22
23function hotLoader(content, context) {
24 const accept = context.locals ? "" : "module.hot.accept(undefined, cssReload);";
25 return `${content}
26 if(module.hot) {
27 // ${Date.now()}
28 var cssReload = require(${(0, _utils.stringifyRequest)(context.context, _path.default.join(__dirname, "hmr/hotModuleReplacement.js"))})(module.id, ${JSON.stringify({ ...context.options,
29 locals: !!context.locals
30 })});
31 module.hot.dispose(cssReload);
32 ${accept}
33 }
34 `;
35}
36
37function pitch(request) {
38 const options = this.getOptions(_loaderOptions.default);
39 const callback = this.async();
40 const optionsFromPlugin = this[_index.pluginSymbol];
41
42 if (!optionsFromPlugin) {
43 callback(new Error("You forgot to add 'mini-css-extract-plugin' plugin (i.e. `{ plugins: [new MiniCssExtractPlugin()] }`), please read https://github.com/webpack-contrib/mini-css-extract-plugin#getting-started"));
44 return;
45 }
46
47 const {
48 webpack
49 } = this._compiler;
50
51 const handleExports = (originalExports, compilation, assets, assetsInfo) => {
52 let locals;
53 let namedExport;
54 const esModule = typeof options.esModule !== "undefined" ? options.esModule : true;
55
56 const addDependencies = dependencies => {
57 if (!Array.isArray(dependencies) && dependencies != null) {
58 throw new Error(`Exported value was not extracted as an array: ${JSON.stringify(dependencies)}`);
59 }
60
61 const identifierCountMap = new Map();
62 const emit = typeof options.emit !== "undefined" ? options.emit : true;
63 let lastDep;
64
65 for (const dependency of dependencies) {
66 if (!dependency.identifier || !emit) {
67 // eslint-disable-next-line no-continue
68 continue;
69 }
70
71 const count = identifierCountMap.get(dependency.identifier) || 0;
72
73 const CssDependency = _index.default.getCssDependency(webpack);
74
75 this._module.addDependency(lastDep = new CssDependency(dependency, dependency.context, count));
76
77 identifierCountMap.set(dependency.identifier, count + 1);
78 }
79
80 if (lastDep && assets) {
81 lastDep.assets = assets;
82 lastDep.assetsInfo = assetsInfo;
83 }
84 };
85
86 try {
87 // eslint-disable-next-line no-underscore-dangle
88 const exports = originalExports.__esModule ? originalExports.default : originalExports;
89 namedExport = // eslint-disable-next-line no-underscore-dangle
90 originalExports.__esModule && (!originalExports.default || !("locals" in originalExports.default));
91
92 if (namedExport) {
93 Object.keys(originalExports).forEach(key => {
94 if (key !== "default") {
95 if (!locals) {
96 locals = {};
97 }
98
99 locals[key] = originalExports[key];
100 }
101 });
102 } else {
103 locals = exports && exports.locals;
104 }
105
106 let dependencies;
107
108 if (!Array.isArray(exports)) {
109 dependencies = [[null, exports]];
110 } else {
111 dependencies = exports.map(([id, content, media, sourceMap, supports, layer]) => {
112 let identifier = id;
113 let context;
114
115 if (compilation) {
116 const module = (0, _utils.findModuleById)(compilation, id);
117 identifier = module.identifier();
118 ({
119 context
120 } = module);
121 } else {
122 // TODO check if this context is used somewhere
123 context = this.rootContext;
124 }
125
126 return {
127 identifier,
128 context,
129 content: Buffer.from(content),
130 media,
131 supports,
132 layer,
133 sourceMap: sourceMap ? Buffer.from(JSON.stringify(sourceMap)) : // eslint-disable-next-line no-undefined
134 undefined
135 };
136 });
137 }
138
139 addDependencies(dependencies);
140 } catch (e) {
141 return callback(e);
142 }
143
144 const result = locals ? namedExport ? Object.keys(locals).map(key => `\nexport var ${key} = ${JSON.stringify(locals[key])};`).join("") : `\n${esModule ? "export default" : "module.exports ="} ${JSON.stringify(locals)};` : esModule ? `\nexport {};` : "";
145 let resultSource = `// extracted by ${_index.pluginName}`;
146 resultSource += this.hot ? hotLoader(result, {
147 context: this.context,
148 options,
149 locals
150 }) : result;
151 return callback(null, resultSource);
152 };
153
154 let {
155 publicPath
156 } = this._compilation.outputOptions;
157
158 if (typeof options.publicPath === "string") {
159 // eslint-disable-next-line prefer-destructuring
160 publicPath = options.publicPath;
161 } else if (typeof options.publicPath === "function") {
162 publicPath = options.publicPath(this.resourcePath, this.rootContext);
163 }
164
165 if (publicPath === "auto") {
166 publicPath = _utils.AUTO_PUBLIC_PATH;
167 }
168
169 if (typeof optionsFromPlugin.experimentalUseImportModule === "undefined" && typeof this.importModule === "function" || optionsFromPlugin.experimentalUseImportModule) {
170 if (!this.importModule) {
171 callback(new Error("You are using 'experimentalUseImportModule' but 'this.importModule' is not available in loader context. You need to have at least webpack 5.33.2."));
172 return;
173 }
174
175 const isAbsolutePublicPath = /^[a-zA-Z][a-zA-Z\d+\-.]*?:/.test(publicPath);
176 const publicPathForExtract = isAbsolutePublicPath ? publicPath : `${_utils.ABSOLUTE_PUBLIC_PATH}${publicPath.replace(/\./g, _utils.SINGLE_DOT_PATH_SEGMENT)}`;
177 this.importModule(`${this.resourcePath}.webpack[javascript/auto]!=!${request}`, {
178 layer: options.layer,
179 publicPath: publicPathForExtract
180 }, (error, exports) => {
181 if (error) {
182 callback(error);
183 return;
184 }
185
186 handleExports(exports);
187 });
188 return;
189 }
190
191 const loaders = this.loaders.slice(this.loaderIndex + 1);
192 this.addDependency(this.resourcePath);
193 const childFilename = "*";
194 const outputOptions = {
195 filename: childFilename,
196 publicPath
197 };
198
199 const childCompiler = this._compilation.createChildCompiler(`${_index.pluginName} ${request}`, outputOptions); // The templates are compiled and executed by NodeJS - similar to server side rendering
200 // Unfortunately this causes issues as some loaders require an absolute URL to support ES Modules
201 // The following config enables relative URL support for the child compiler
202
203
204 childCompiler.options.module = { ...childCompiler.options.module
205 };
206 childCompiler.options.module.parser = { ...childCompiler.options.module.parser
207 };
208 childCompiler.options.module.parser.javascript = { ...childCompiler.options.module.parser.javascript,
209 url: "relative"
210 };
211 const {
212 NodeTemplatePlugin
213 } = webpack.node;
214 const {
215 NodeTargetPlugin
216 } = webpack.node;
217 new NodeTemplatePlugin(outputOptions).apply(childCompiler);
218 new NodeTargetPlugin().apply(childCompiler);
219 const {
220 EntryOptionPlugin
221 } = webpack;
222 const {
223 library: {
224 EnableLibraryPlugin
225 }
226 } = webpack;
227 new EnableLibraryPlugin("commonjs2").apply(childCompiler);
228 EntryOptionPlugin.applyEntryOption(childCompiler, this.context, {
229 child: {
230 library: {
231 type: "commonjs2"
232 },
233 import: [`!!${request}`]
234 }
235 });
236 const {
237 LimitChunkCountPlugin
238 } = webpack.optimize;
239 new LimitChunkCountPlugin({
240 maxChunks: 1
241 }).apply(childCompiler);
242 const {
243 NormalModule
244 } = webpack;
245 childCompiler.hooks.thisCompilation.tap(`${_index.pluginName} loader`, compilation => {
246 const normalModuleHook = NormalModule.getCompilationHooks(compilation).loader;
247 normalModuleHook.tap(`${_index.pluginName} loader`, (loaderContext, module) => {
248 if (module.request === request) {
249 // eslint-disable-next-line no-param-reassign
250 module.loaders = loaders.map(loader => {
251 return {
252 loader: loader.path,
253 options: loader.options,
254 ident: loader.ident
255 };
256 });
257 }
258 });
259 });
260 let source;
261 childCompiler.hooks.compilation.tap(_index.pluginName, compilation => {
262 compilation.hooks.processAssets.tap(_index.pluginName, () => {
263 source = compilation.assets[childFilename] && compilation.assets[childFilename].source(); // Remove all chunk assets
264
265 compilation.chunks.forEach(chunk => {
266 chunk.files.forEach(file => {
267 compilation.deleteAsset(file);
268 });
269 });
270 });
271 });
272 childCompiler.runAsChild((error, entries, compilation) => {
273 if (error) {
274 return callback(error);
275 }
276
277 if (compilation.errors.length > 0) {
278 return callback(compilation.errors[0]);
279 }
280
281 const assets = Object.create(null);
282 const assetsInfo = new Map();
283
284 for (const asset of compilation.getAssets()) {
285 assets[asset.name] = asset.source;
286 assetsInfo.set(asset.name, asset.info);
287 }
288
289 compilation.fileDependencies.forEach(dep => {
290 this.addDependency(dep);
291 }, this);
292 compilation.contextDependencies.forEach(dep => {
293 this.addContextDependency(dep);
294 }, this);
295
296 if (!source) {
297 return callback(new Error("Didn't get a result from child compiler"));
298 }
299
300 let originalExports;
301
302 try {
303 originalExports = (0, _utils.evalModuleCode)(this, source, request);
304 } catch (e) {
305 return callback(e);
306 }
307
308 return handleExports(originalExports, compilation, assets, assetsInfo);
309 });
310} // eslint-disable-next-line func-names
311
312
313function _default() {}
\No newline at end of file