loader.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.pitch = pitch;
  6. exports.default = _default;
  7. var _module = _interopRequireDefault(require("module"));
  8. var _path = _interopRequireDefault(require("path"));
  9. var _loaderUtils = _interopRequireDefault(require("loader-utils"));
  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 _schemaUtils = _interopRequireDefault(require("schema-utils"));
  16. var _CssDependency = _interopRequireDefault(require("./CssDependency"));
  17. var _options = _interopRequireDefault(require("./options.json"));
  18. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  19. 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; }
  20. 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; }
  21. 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; }
  22. const pluginName = 'mini-css-extract-plugin';
  23. function 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(${_loaderUtils.default.stringifyRequest(context.context, _path.default.join(__dirname, 'hmr/hotModuleReplacement.js'))})(module.id, ${JSON.stringify(_objectSpread({}, context.options, {
  29. locals: !!context.locals
  30. }))});
  31. module.hot.dispose(cssReload);
  32. ${accept}
  33. }
  34. `;
  35. }
  36. function evalModuleCode(loaderContext, code, filename) {
  37. const module = new _module.default(filename, loaderContext);
  38. module.paths = _module.default._nodeModulePaths(loaderContext.context); // eslint-disable-line no-underscore-dangle
  39. module.filename = filename;
  40. module._compile(code, filename); // eslint-disable-line no-underscore-dangle
  41. return module.exports;
  42. }
  43. function findModuleById(modules, id) {
  44. for (const module of modules) {
  45. if (module.id === id) {
  46. return module;
  47. }
  48. }
  49. return null;
  50. }
  51. function pitch(request) {
  52. const options = _loaderUtils.default.getOptions(this) || {};
  53. (0, _schemaUtils.default)(_options.default, options, 'Mini CSS Extract Plugin Loader');
  54. const loaders = this.loaders.slice(this.loaderIndex + 1);
  55. this.addDependency(this.resourcePath);
  56. const childFilename = '*';
  57. 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;
  58. const outputOptions = {
  59. filename: childFilename,
  60. publicPath
  61. };
  62. const childCompiler = this._compilation.createChildCompiler(`${pluginName} ${request}`, outputOptions);
  63. new _NodeTemplatePlugin.default(outputOptions).apply(childCompiler);
  64. new _LibraryTemplatePlugin.default(null, 'commonjs2').apply(childCompiler);
  65. new _NodeTargetPlugin.default().apply(childCompiler);
  66. new _SingleEntryPlugin.default(this.context, `!!${request}`, pluginName).apply(childCompiler);
  67. new _LimitChunkCountPlugin.default({
  68. maxChunks: 1
  69. }).apply(childCompiler);
  70. childCompiler.hooks.thisCompilation.tap(`${pluginName} loader`, compilation => {
  71. compilation.hooks.normalModuleLoader.tap(`${pluginName} loader`, (loaderContext, module) => {
  72. // eslint-disable-next-line no-param-reassign
  73. loaderContext.emitFile = this.emitFile;
  74. if (module.request === request) {
  75. // eslint-disable-next-line no-param-reassign
  76. module.loaders = loaders.map(loader => {
  77. return {
  78. loader: loader.path,
  79. options: loader.options,
  80. ident: loader.ident
  81. };
  82. });
  83. }
  84. });
  85. });
  86. let source;
  87. childCompiler.hooks.afterCompile.tap(pluginName, compilation => {
  88. source = compilation.assets[childFilename] && compilation.assets[childFilename].source(); // Remove all chunk assets
  89. compilation.chunks.forEach(chunk => {
  90. chunk.files.forEach(file => {
  91. delete compilation.assets[file]; // eslint-disable-line no-param-reassign
  92. });
  93. });
  94. });
  95. const callback = this.async();
  96. childCompiler.runAsChild((err, entries, compilation) => {
  97. const addDependencies = dependencies => {
  98. if (!Array.isArray(dependencies) && dependencies != null) {
  99. throw new Error(`Exported value was not extracted as an array: ${JSON.stringify(dependencies)}`);
  100. }
  101. const identifierCountMap = new Map();
  102. for (const dependency of dependencies) {
  103. const count = identifierCountMap.get(dependency.identifier) || 0;
  104. this._module.addDependency(new _CssDependency.default(dependency, dependency.context, count));
  105. identifierCountMap.set(dependency.identifier, count + 1);
  106. }
  107. };
  108. if (err) {
  109. return callback(err);
  110. }
  111. if (compilation.errors.length > 0) {
  112. return callback(compilation.errors[0]);
  113. }
  114. compilation.fileDependencies.forEach(dep => {
  115. this.addDependency(dep);
  116. }, this);
  117. compilation.contextDependencies.forEach(dep => {
  118. this.addContextDependency(dep);
  119. }, this);
  120. if (!source) {
  121. return callback(new Error("Didn't get a result from child compiler"));
  122. }
  123. let locals;
  124. try {
  125. let dependencies;
  126. let exports = evalModuleCode(this, source, request); // eslint-disable-next-line no-underscore-dangle
  127. exports = exports.__esModule ? exports.default : exports;
  128. locals = exports && exports.locals;
  129. if (!Array.isArray(exports)) {
  130. dependencies = [[null, exports]];
  131. } else {
  132. dependencies = exports.map(([id, content, media, sourceMap]) => {
  133. const module = findModuleById(compilation.modules, id);
  134. return {
  135. identifier: module.identifier(),
  136. context: module.context,
  137. content,
  138. media,
  139. sourceMap
  140. };
  141. });
  142. }
  143. addDependencies(dependencies);
  144. } catch (e) {
  145. return callback(e);
  146. }
  147. const esModule = typeof options.esModule !== 'undefined' ? options.esModule : false;
  148. const result = locals ? `\n${esModule ? 'export default' : 'module.exports ='} ${JSON.stringify(locals)};` : '';
  149. let resultSource = `// extracted by ${pluginName}`;
  150. resultSource += options.hmr ? hotLoader(result, {
  151. context: this.context,
  152. options,
  153. locals
  154. }) : result;
  155. return callback(null, resultSource);
  156. });
  157. }
  158. function _default() {}