index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6. var _fs = require('fs');
  7. var _fs2 = _interopRequireDefault(_fs);
  8. var _path = require('path');
  9. var _path2 = _interopRequireDefault(_path);
  10. var _Chunk = require('webpack/lib/Chunk');
  11. var _Chunk2 = _interopRequireDefault(_Chunk);
  12. var _webpackSources = require('webpack-sources');
  13. var _async = require('async');
  14. var _async2 = _interopRequireDefault(_async);
  15. var _loaderUtils = require('loader-utils');
  16. var _loaderUtils2 = _interopRequireDefault(_loaderUtils);
  17. var _schemaUtils = require('schema-utils');
  18. var _schemaUtils2 = _interopRequireDefault(_schemaUtils);
  19. var _ExtractTextPluginCompilation = require('./lib/ExtractTextPluginCompilation');
  20. var _ExtractTextPluginCompilation2 = _interopRequireDefault(_ExtractTextPluginCompilation);
  21. var _OrderUndefinedError = require('./lib/OrderUndefinedError');
  22. var _OrderUndefinedError2 = _interopRequireDefault(_OrderUndefinedError);
  23. var _helpers = require('./lib/helpers');
  24. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  26. var NS = _fs2.default.realpathSync(__dirname);
  27. var nextId = 0;
  28. var ExtractTextPlugin = function () {
  29. function ExtractTextPlugin(options) {
  30. _classCallCheck(this, ExtractTextPlugin);
  31. if ((0, _helpers.isString)(options)) {
  32. options = { filename: options };
  33. } else {
  34. (0, _schemaUtils2.default)(_path2.default.resolve(__dirname, '../schema/plugin.json'), options, 'Extract Text Plugin');
  35. }
  36. this.filename = options.filename;
  37. this.id = options.id != null ? options.id : ++nextId;
  38. this.options = {};
  39. (0, _helpers.mergeOptions)(this.options, options);
  40. delete this.options.filename;
  41. delete this.options.id;
  42. }
  43. _createClass(ExtractTextPlugin, [{
  44. key: 'applyAdditionalInformation',
  45. value: function applyAdditionalInformation(source, info) {
  46. if (info) {
  47. return new _webpackSources.ConcatSource(`@media ${info[0]} {`, source, '}');
  48. }
  49. return source;
  50. }
  51. }, {
  52. key: 'loader',
  53. value: function loader(options) {
  54. return ExtractTextPlugin.loader((0, _helpers.mergeOptions)({ id: this.id }, options));
  55. }
  56. }, {
  57. key: 'mergeNonInitialChunks',
  58. value: function mergeNonInitialChunks(chunk, intoChunk, checkedChunks) {
  59. var _this = this;
  60. if (!intoChunk) {
  61. checkedChunks = [];
  62. chunk.chunks.forEach(function (c) {
  63. if ((0, _helpers.isInitialOrHasNoParents)(c)) return;
  64. _this.mergeNonInitialChunks(c, chunk, checkedChunks);
  65. }, this);
  66. } else if (checkedChunks.indexOf(chunk) < 0) {
  67. checkedChunks.push(chunk);
  68. chunk.forEachModule(function (module) {
  69. intoChunk.addModule(module);
  70. module.addChunk(intoChunk);
  71. });
  72. chunk.chunks.forEach(function (c) {
  73. if ((0, _helpers.isInitialOrHasNoParents)(c)) return;
  74. _this.mergeNonInitialChunks(c, intoChunk, checkedChunks);
  75. }, this);
  76. }
  77. }
  78. }, {
  79. key: 'renderExtractedChunk',
  80. value: function renderExtractedChunk(chunk) {
  81. var _this2 = this;
  82. var source = new _webpackSources.ConcatSource();
  83. chunk.forEachModule(function (module) {
  84. var moduleSource = module.source();
  85. source.add(_this2.applyAdditionalInformation(moduleSource, module.additionalInformation));
  86. }, this);
  87. return source;
  88. }
  89. }, {
  90. key: 'extract',
  91. value: function extract(options) {
  92. if (Array.isArray(options) || (0, _helpers.isString)(options) || typeof options.options === 'object' || typeof options.query === 'object') {
  93. options = { use: options };
  94. } else {
  95. (0, _schemaUtils2.default)(_path2.default.resolve(__dirname, '../schema/loader.json'), options, 'Extract Text Plugin (Loader)');
  96. }
  97. var loader = options.use;
  98. var before = options.fallback || [];
  99. if ((0, _helpers.isString)(loader)) {
  100. loader = loader.split('!');
  101. }
  102. if ((0, _helpers.isString)(before)) {
  103. before = before.split('!');
  104. } else if (!Array.isArray(before)) {
  105. before = [before];
  106. }
  107. options = (0, _helpers.mergeOptions)({ omit: before.length, remove: true }, options);
  108. delete options.use;
  109. delete options.fallback;
  110. return [this.loader(options)].concat(before, loader).map(_helpers.getLoaderObject);
  111. }
  112. }, {
  113. key: 'apply',
  114. value: function apply(compiler) {
  115. var _this3 = this;
  116. var options = this.options;
  117. compiler.plugin('this-compilation', function (compilation) {
  118. var extractCompilation = new _ExtractTextPluginCompilation2.default();
  119. compilation.plugin('normal-module-loader', function (loaderContext, module) {
  120. loaderContext[NS] = function (content, opt) {
  121. if (options.disable) {
  122. return false;
  123. }
  124. if (!Array.isArray(content) && content != null) {
  125. throw new Error(`Exported value was not extracted as an array: ${JSON.stringify(content)}`);
  126. }
  127. module[NS] = {
  128. content,
  129. options: opt || {}
  130. };
  131. return options.allChunks || module[`${NS}/extract`]; // eslint-disable-line no-path-concat
  132. };
  133. });
  134. var filename = _this3.filename;
  135. var id = _this3.id;
  136. var extractedChunks = void 0;
  137. compilation.plugin('optimize-tree', function (chunks, modules, callback) {
  138. extractedChunks = chunks.map(function () {
  139. return new _Chunk2.default();
  140. });
  141. chunks.forEach(function (chunk, i) {
  142. var extractedChunk = extractedChunks[i];
  143. extractedChunk.index = i;
  144. extractedChunk.originalChunk = chunk;
  145. extractedChunk.name = chunk.name;
  146. extractedChunk.entrypoints = chunk.entrypoints;
  147. chunk.chunks.forEach(function (c) {
  148. extractedChunk.addChunk(extractedChunks[chunks.indexOf(c)]);
  149. });
  150. chunk.parents.forEach(function (c) {
  151. extractedChunk.addParent(extractedChunks[chunks.indexOf(c)]);
  152. });
  153. });
  154. _async2.default.forEach(chunks, function (chunk, callback) {
  155. // eslint-disable-line no-shadow
  156. var extractedChunk = extractedChunks[chunks.indexOf(chunk)];
  157. var shouldExtract = !!(options.allChunks || (0, _helpers.isInitialOrHasNoParents)(chunk));
  158. chunk.sortModules();
  159. _async2.default.forEach(chunk.mapModules(function (c) {
  160. return c;
  161. }), function (module, callback) {
  162. // eslint-disable-line no-shadow
  163. var meta = module[NS];
  164. if (meta && (!meta.options.id || meta.options.id === id)) {
  165. var wasExtracted = Array.isArray(meta.content);
  166. if (shouldExtract !== wasExtracted) {
  167. module[`${NS}/extract`] = shouldExtract; // eslint-disable-line no-path-concat
  168. compilation.rebuildModule(module, function (err) {
  169. if (err) {
  170. compilation.errors.push(err);
  171. return callback();
  172. }
  173. meta = module[NS];
  174. // Error out if content is not an array and is not null
  175. if (!Array.isArray(meta.content) && meta.content != null) {
  176. err = new Error(`${module.identifier()} doesn't export content`);
  177. compilation.errors.push(err);
  178. return callback();
  179. }
  180. if (meta.content) {
  181. extractCompilation.addResultToChunk(module.identifier(), meta.content, module, extractedChunk);
  182. }
  183. callback();
  184. });
  185. } else {
  186. if (meta.content) {
  187. extractCompilation.addResultToChunk(module.identifier(), meta.content, module, extractedChunk);
  188. }
  189. callback();
  190. }
  191. } else callback();
  192. }, function (err) {
  193. if (err) return callback(err);
  194. callback();
  195. });
  196. }, function (err) {
  197. if (err) return callback(err);
  198. extractedChunks.forEach(function (extractedChunk) {
  199. if ((0, _helpers.isInitialOrHasNoParents)(extractedChunk)) {
  200. _this3.mergeNonInitialChunks(extractedChunk);
  201. }
  202. }, _this3);
  203. extractedChunks.forEach(function (extractedChunk) {
  204. if (!(0, _helpers.isInitialOrHasNoParents)(extractedChunk)) {
  205. extractedChunk.forEachModule(function (module) {
  206. extractedChunk.removeModule(module);
  207. });
  208. }
  209. });
  210. compilation.applyPlugins('optimize-extracted-chunks', extractedChunks);
  211. callback();
  212. });
  213. });
  214. compilation.plugin('additional-assets', function (callback) {
  215. extractedChunks.forEach(function (extractedChunk) {
  216. if (extractedChunk.getNumberOfModules()) {
  217. extractedChunk.sortModules(function (a, b) {
  218. if (!options.ignoreOrder && (0, _helpers.isInvalidOrder)(a, b)) {
  219. compilation.errors.push(new _OrderUndefinedError2.default(a.getOriginalModule()));
  220. compilation.errors.push(new _OrderUndefinedError2.default(b.getOriginalModule()));
  221. }
  222. return (0, _helpers.getOrder)(a, b);
  223. });
  224. var chunk = extractedChunk.originalChunk;
  225. var source = _this3.renderExtractedChunk(extractedChunk);
  226. var getPath = function getPath(format) {
  227. return compilation.getPath(format, {
  228. chunk
  229. }).replace(/\[(?:(\w+):)?contenthash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, function () {
  230. // eslint-disable-line func-names
  231. return _loaderUtils2.default.getHashDigest(source.source(), arguments[1], arguments[2], parseInt(arguments[3], 10));
  232. });
  233. };
  234. var file = (0, _helpers.isFunction)(filename) ? filename(getPath) : getPath(filename);
  235. compilation.assets[file] = source;
  236. chunk.files.push(file);
  237. }
  238. }, _this3);
  239. callback();
  240. });
  241. });
  242. }
  243. }], [{
  244. key: 'loader',
  245. value: function loader(options) {
  246. return { loader: require.resolve('./loader'), options };
  247. }
  248. }]);
  249. return ExtractTextPlugin;
  250. }();
  251. ExtractTextPlugin.extract = ExtractTextPlugin.prototype.extract.bind(ExtractTextPlugin);
  252. exports.default = ExtractTextPlugin;