loader.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 _webpack = require("webpack");
  10. var _NodeTemplatePlugin = _interopRequireDefault(require("webpack/lib/node/NodeTemplatePlugin"));
  11. var _NodeTargetPlugin = _interopRequireDefault(require("webpack/lib/node/NodeTargetPlugin"));
  12. var _LibraryTemplatePlugin = _interopRequireDefault(require("webpack/lib/LibraryTemplatePlugin"));
  13. var _SingleEntryPlugin = _interopRequireDefault(require("webpack/lib/SingleEntryPlugin"));
  14. var _LimitChunkCountPlugin = _interopRequireDefault(require("webpack/lib/optimize/LimitChunkCountPlugin"));
  15. var _NormalModule = _interopRequireDefault(require("webpack/lib/NormalModule"));
  16. var _schemaUtils = _interopRequireDefault(require("schema-utils"));
  17. var _CssDependency = _interopRequireDefault(require("./CssDependency"));
  18. var _utils = require("./utils");
  19. var _loaderOptions = _interopRequireDefault(require("./loader-options.json"));
  20. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  21. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  22. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  23. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  24. const pluginName = 'mini-css-extract-plugin';
  25. const isWebpack4 = _webpack.version[0] === '4';
  26. function hotLoader(content, context) {
  27. const accept = context.locals ? '' : 'module.hot.accept(undefined, cssReload);';
  28. return `${content}
  29. if(module.hot) {
  30. // ${Date.now()}
  31. var cssReload = require(${_loaderUtils.default.stringifyRequest(context.context, _path.default.join(__dirname, 'hmr/hotModuleReplacement.js'))})(module.id, ${JSON.stringify(_objectSpread(_objectSpread({}, context.options), {}, {
  32. locals: !!context.locals
  33. }))});
  34. module.hot.dispose(cssReload);
  35. ${accept}
  36. }
  37. `;
  38. }
  39. function pitch(request) {
  40. const options = _loaderUtils.default.getOptions(this) || {};
  41. (0, _schemaUtils.default)(_loaderOptions.default, options, 'Mini CSS Extract Plugin Loader');
  42. const loaders = this.loaders.slice(this.loaderIndex + 1);
  43. this.addDependency(this.resourcePath);
  44. const childFilename = '*';
  45. const publicPath = typeof options.publicPath === 'string' ? options.publicPath === '' || options.publicPath.endsWith('/') ? options.publicPath : `${options.publicPath}/` : typeof options.publicPath === 'function' ? options.publicPath(this.resourcePath, this.rootContext) : this._compilation.outputOptions.publicPath;
  46. const outputOptions = {
  47. filename: childFilename,
  48. publicPath
  49. };
  50. const childCompiler = this._compilation.createChildCompiler(`${pluginName} ${request}`, outputOptions);
  51. new _NodeTemplatePlugin.default(outputOptions).apply(childCompiler);
  52. new _LibraryTemplatePlugin.default(null, 'commonjs2').apply(childCompiler);
  53. new _NodeTargetPlugin.default().apply(childCompiler);
  54. new _SingleEntryPlugin.default(this.context, `!!${request}`, pluginName).apply(childCompiler);
  55. new _LimitChunkCountPlugin.default({
  56. maxChunks: 1
  57. }).apply(childCompiler);
  58. childCompiler.hooks.thisCompilation.tap(`${pluginName} loader`, compilation => {
  59. const normalModuleHook = typeof _NormalModule.default.getCompilationHooks !== 'undefined' ? _NormalModule.default.getCompilationHooks(compilation).loader : compilation.hooks.normalModuleLoader;
  60. normalModuleHook.tap(`${pluginName} loader`, (loaderContext, module) => {
  61. // eslint-disable-next-line no-param-reassign
  62. loaderContext.emitFile = this.emitFile;
  63. if (module.request === request) {
  64. // eslint-disable-next-line no-param-reassign
  65. module.loaders = loaders.map(loader => {
  66. return {
  67. loader: loader.path,
  68. options: loader.options,
  69. ident: loader.ident
  70. };
  71. });
  72. }
  73. });
  74. });
  75. let source;
  76. if (isWebpack4) {
  77. childCompiler.hooks.afterCompile.tap(pluginName, compilation => {
  78. source = compilation.assets[childFilename] && compilation.assets[childFilename].source(); // Remove all chunk assets
  79. compilation.chunks.forEach(chunk => {
  80. chunk.files.forEach(file => {
  81. delete compilation.assets[file]; // eslint-disable-line no-param-reassign
  82. });
  83. });
  84. });
  85. } else {
  86. childCompiler.hooks.compilation.tap(pluginName, compilation => {
  87. compilation.hooks.processAssets.tap(pluginName, () => {
  88. source = compilation.assets[childFilename] && compilation.assets[childFilename].source(); // Remove all chunk assets
  89. compilation.chunks.forEach(chunk => {
  90. chunk.files.forEach(file => {
  91. compilation.deleteAsset(file);
  92. });
  93. });
  94. });
  95. });
  96. }
  97. const callback = this.async();
  98. childCompiler.runAsChild((err, entries, compilation) => {
  99. const addDependencies = dependencies => {
  100. if (!Array.isArray(dependencies) && dependencies != null) {
  101. throw new Error(`Exported value was not extracted as an array: ${JSON.stringify(dependencies)}`);
  102. }
  103. const identifierCountMap = new Map();
  104. for (const dependency of dependencies) {
  105. const count = identifierCountMap.get(dependency.identifier) || 0;
  106. this._module.addDependency(new _CssDependency.default(dependency, dependency.context, count));
  107. identifierCountMap.set(dependency.identifier, count + 1);
  108. }
  109. };
  110. if (err) {
  111. return callback(err);
  112. }
  113. if (compilation.errors.length > 0) {
  114. return callback(compilation.errors[0]);
  115. }
  116. compilation.fileDependencies.forEach(dep => {
  117. this.addDependency(dep);
  118. }, this);
  119. compilation.contextDependencies.forEach(dep => {
  120. this.addContextDependency(dep);
  121. }, this);
  122. if (!source) {
  123. return callback(new Error("Didn't get a result from child compiler"));
  124. }
  125. let locals;
  126. const esModule = typeof options.esModule !== 'undefined' ? options.esModule : false;
  127. const namedExport = esModule && options.modules && options.modules.namedExport;
  128. try {
  129. const originalExports = (0, _utils.evalModuleCode)(this, source, request); // eslint-disable-next-line no-underscore-dangle
  130. exports = originalExports.__esModule ? originalExports.default : originalExports;
  131. if (namedExport) {
  132. Object.keys(originalExports).forEach(key => {
  133. if (key !== 'default') {
  134. if (!locals) locals = {};
  135. locals[key] = originalExports[key];
  136. }
  137. });
  138. } else {
  139. locals = exports && exports.locals;
  140. }
  141. let dependencies;
  142. if (!Array.isArray(exports)) {
  143. dependencies = [[null, exports]];
  144. } else {
  145. dependencies = exports.map(([id, content, media, sourceMap]) => {
  146. const module = (0, _utils.findModuleById)(compilation, id);
  147. return {
  148. identifier: module.identifier(),
  149. context: module.context,
  150. content,
  151. media,
  152. sourceMap
  153. };
  154. });
  155. }
  156. addDependencies(dependencies);
  157. } catch (e) {
  158. return callback(e);
  159. }
  160. const result = locals ? namedExport ? Object.keys(locals).map(key => `\nexport const ${key} = ${JSON.stringify(locals[key])};`).join('') : `\n${esModule ? 'export default' : 'module.exports ='} ${JSON.stringify(locals)};` : esModule ? `\nexport {};` : '';
  161. let resultSource = `// extracted by ${pluginName}`;
  162. resultSource += options.hmr ? hotLoader(result, {
  163. context: this.context,
  164. options,
  165. locals
  166. }) : result;
  167. return callback(null, resultSource);
  168. });
  169. } // eslint-disable-next-line func-names
  170. function _default() {}