loader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.pitch = pitch;
  6. exports.default = _default;
  7. var _path = _interopRequireDefault(require("path"));
  8. var _loaderUtils = _interopRequireDefault(require("loader-utils"));
  9. var _schemaUtils = require("schema-utils");
  10. var _utils = require("./utils");
  11. var _loaderOptions = _interopRequireDefault(require("./loader-options.json"));
  12. var _index = _interopRequireWildcard(require("./index"));
  13. function _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); }
  14. function _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; }
  15. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  16. function hotLoader(content, context) {
  17. const accept = context.locals ? '' : 'module.hot.accept(undefined, cssReload);';
  18. return `${content}
  19. if(module.hot) {
  20. // ${Date.now()}
  21. var cssReload = require(${_loaderUtils.default.stringifyRequest(context.context, _path.default.join(__dirname, 'hmr/hotModuleReplacement.js'))})(module.id, ${JSON.stringify({ ...context.options,
  22. locals: !!context.locals
  23. })});
  24. module.hot.dispose(cssReload);
  25. ${accept}
  26. }
  27. `;
  28. }
  29. function pitch(request) {
  30. const options = _loaderUtils.default.getOptions(this) || {};
  31. (0, _schemaUtils.validate)(_loaderOptions.default, options, {
  32. name: 'Mini CSS Extract Plugin Loader',
  33. baseDataPath: 'options'
  34. });
  35. const callback = this.async();
  36. const optionsFromPlugin = this[_index.pluginSymbol];
  37. if (!optionsFromPlugin) {
  38. 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"));
  39. return;
  40. } // TODO simplify after drop webpack v4
  41. // eslint-disable-next-line global-require
  42. const webpack = this._compiler.webpack || require('webpack');
  43. const handleExports = (originalExports, compilation, assets, assetsInfo) => {
  44. let locals;
  45. const esModule = typeof options.esModule !== 'undefined' ? options.esModule : true;
  46. const namedExport = esModule && options.modules && options.modules.namedExport;
  47. const addDependencies = dependencies => {
  48. if (!Array.isArray(dependencies) && dependencies != null) {
  49. throw new Error(`Exported value was not extracted as an array: ${JSON.stringify(dependencies)}`);
  50. }
  51. const identifierCountMap = new Map();
  52. const emit = typeof options.emit !== 'undefined' ? options.emit : true;
  53. let lastDep;
  54. for (const dependency of dependencies) {
  55. if (!dependency.identifier || !emit) {
  56. // eslint-disable-next-line no-continue
  57. continue;
  58. }
  59. const count = identifierCountMap.get(dependency.identifier) || 0;
  60. const CssDependency = _index.default.getCssDependency(webpack);
  61. this._module.addDependency(lastDep = new CssDependency(dependency, dependency.context, count));
  62. identifierCountMap.set(dependency.identifier, count + 1);
  63. }
  64. if (lastDep && assets) {
  65. lastDep.assets = assets;
  66. lastDep.assetsInfo = assetsInfo;
  67. }
  68. };
  69. try {
  70. // eslint-disable-next-line no-underscore-dangle
  71. const exports = originalExports.__esModule ? originalExports.default : originalExports;
  72. if (namedExport) {
  73. Object.keys(originalExports).forEach(key => {
  74. if (key !== 'default') {
  75. if (!locals) {
  76. locals = {};
  77. }
  78. locals[key] = originalExports[key];
  79. }
  80. });
  81. } else {
  82. locals = exports && exports.locals;
  83. }
  84. let dependencies;
  85. if (!Array.isArray(exports)) {
  86. dependencies = [[null, exports]];
  87. } else {
  88. dependencies = exports.map(([id, content, media, sourceMap]) => {
  89. let identifier = id;
  90. let context;
  91. if (compilation) {
  92. const module = (0, _utils.findModuleById)(compilation, id);
  93. identifier = module.identifier();
  94. ({
  95. context
  96. } = module);
  97. } else {
  98. // TODO check if this context is used somewhere
  99. context = this.rootContext;
  100. }
  101. return {
  102. identifier,
  103. context,
  104. content: Buffer.from(content),
  105. media,
  106. sourceMap: sourceMap ? Buffer.from(JSON.stringify(sourceMap)) : // eslint-disable-next-line no-undefined
  107. undefined
  108. };
  109. });
  110. }
  111. addDependencies(dependencies);
  112. } catch (e) {
  113. return callback(e);
  114. }
  115. 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 {};` : '';
  116. let resultSource = `// extracted by ${_index.pluginName}`;
  117. resultSource += this.hot ? hotLoader(result, {
  118. context: this.context,
  119. options,
  120. locals
  121. }) : result;
  122. return callback(null, resultSource);
  123. };
  124. const publicPath = typeof options.publicPath === 'string' ? options.publicPath === 'auto' ? '' : options.publicPath === '' || options.publicPath.endsWith('/') ? options.publicPath : `${options.publicPath}/` : typeof options.publicPath === 'function' ? options.publicPath(this.resourcePath, this.rootContext) : this._compilation.outputOptions.publicPath === 'auto' ? '' : this._compilation.outputOptions.publicPath;
  125. if (optionsFromPlugin.experimentalUseImportModule) {
  126. if (!this.importModule) {
  127. 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."));
  128. return;
  129. }
  130. this.importModule(`${this.resourcePath}.webpack[javascript/auto]!=!${request}`, {
  131. layer: options.layer,
  132. publicPath
  133. }, (err, exports) => {
  134. if (err) {
  135. callback(err);
  136. return;
  137. }
  138. handleExports(exports);
  139. });
  140. return;
  141. }
  142. const loaders = this.loaders.slice(this.loaderIndex + 1);
  143. this.addDependency(this.resourcePath);
  144. const childFilename = '*';
  145. const outputOptions = {
  146. filename: childFilename,
  147. publicPath
  148. };
  149. const childCompiler = this._compilation.createChildCompiler(`${_index.pluginName} ${request}`, outputOptions); // The templates are compiled and executed by NodeJS - similar to server side rendering
  150. // Unfortunately this causes issues as some loaders require an absolute URL to support ES Modules
  151. // The following config enables relative URL support for the child compiler
  152. childCompiler.options.module = { ...childCompiler.options.module
  153. };
  154. childCompiler.options.module.parser = { ...childCompiler.options.module.parser
  155. };
  156. childCompiler.options.module.parser.javascript = { ...childCompiler.options.module.parser.javascript,
  157. url: 'relative'
  158. };
  159. const {
  160. NodeTemplatePlugin
  161. } = webpack.node;
  162. const NodeTargetPlugin = webpack.node.NodeTargetPlugin ? webpack.node.NodeTargetPlugin : // eslint-disable-next-line global-require
  163. require('webpack/lib/node/NodeTargetPlugin');
  164. new NodeTemplatePlugin(outputOptions).apply(childCompiler);
  165. new NodeTargetPlugin().apply(childCompiler);
  166. const {
  167. EntryOptionPlugin
  168. } = webpack;
  169. if (EntryOptionPlugin) {
  170. const {
  171. library: {
  172. EnableLibraryPlugin
  173. }
  174. } = webpack;
  175. new EnableLibraryPlugin('commonjs2').apply(childCompiler);
  176. EntryOptionPlugin.applyEntryOption(childCompiler, this.context, {
  177. child: {
  178. library: {
  179. type: 'commonjs2'
  180. },
  181. import: [`!!${request}`]
  182. }
  183. });
  184. } else {
  185. const {
  186. LibraryTemplatePlugin,
  187. SingleEntryPlugin
  188. } = webpack;
  189. new LibraryTemplatePlugin(null, 'commonjs2').apply(childCompiler);
  190. new SingleEntryPlugin(this.context, `!!${request}`, _index.pluginName).apply(childCompiler);
  191. }
  192. const {
  193. LimitChunkCountPlugin
  194. } = webpack.optimize;
  195. new LimitChunkCountPlugin({
  196. maxChunks: 1
  197. }).apply(childCompiler);
  198. const NormalModule = webpack.NormalModule ? webpack.NormalModule : // eslint-disable-next-line global-require
  199. require('webpack/lib/NormalModule');
  200. childCompiler.hooks.thisCompilation.tap(`${_index.pluginName} loader`, compilation => {
  201. const normalModuleHook = typeof NormalModule.getCompilationHooks !== 'undefined' ? NormalModule.getCompilationHooks(compilation).loader : compilation.hooks.normalModuleLoader;
  202. normalModuleHook.tap(`${_index.pluginName} loader`, (loaderContext, module) => {
  203. if (module.request === request) {
  204. // eslint-disable-next-line no-param-reassign
  205. module.loaders = loaders.map(loader => {
  206. return {
  207. loader: loader.path,
  208. options: loader.options,
  209. ident: loader.ident
  210. };
  211. });
  212. }
  213. });
  214. });
  215. let source;
  216. const isWebpack4 = childCompiler.webpack ? false : typeof childCompiler.resolvers !== 'undefined';
  217. if (isWebpack4) {
  218. childCompiler.hooks.afterCompile.tap(_index.pluginName, compilation => {
  219. source = compilation.assets[childFilename] && compilation.assets[childFilename].source(); // Remove all chunk assets
  220. compilation.chunks.forEach(chunk => {
  221. chunk.files.forEach(file => {
  222. delete compilation.assets[file]; // eslint-disable-line no-param-reassign
  223. });
  224. });
  225. });
  226. } else {
  227. childCompiler.hooks.compilation.tap(_index.pluginName, compilation => {
  228. compilation.hooks.processAssets.tap(_index.pluginName, () => {
  229. source = compilation.assets[childFilename] && compilation.assets[childFilename].source(); // console.log(source);
  230. // Remove all chunk assets
  231. compilation.chunks.forEach(chunk => {
  232. chunk.files.forEach(file => {
  233. compilation.deleteAsset(file);
  234. });
  235. });
  236. });
  237. });
  238. }
  239. childCompiler.runAsChild((error, entries, compilation) => {
  240. const assets = Object.create(null);
  241. const assetsInfo = new Map();
  242. for (const asset of compilation.getAssets()) {
  243. assets[asset.name] = asset.source;
  244. assetsInfo.set(asset.name, asset.info);
  245. }
  246. if (error) {
  247. return callback(error);
  248. }
  249. if (compilation.errors.length > 0) {
  250. return callback(compilation.errors[0]);
  251. }
  252. compilation.fileDependencies.forEach(dep => {
  253. this.addDependency(dep);
  254. }, this);
  255. compilation.contextDependencies.forEach(dep => {
  256. this.addContextDependency(dep);
  257. }, this);
  258. if (!source) {
  259. return callback(new Error("Didn't get a result from child compiler"));
  260. }
  261. let originalExports;
  262. try {
  263. originalExports = (0, _utils.evalModuleCode)(this, source, request);
  264. } catch (e) {
  265. return callback(e);
  266. }
  267. return handleExports(originalExports, compilation, assets, assetsInfo);
  268. });
  269. } // eslint-disable-next-line func-names
  270. function _default() {}