index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 = _path2.default.dirname(_fs2.default.realpathSync(__filename));
  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. // A stricter `shouldExtract !== wasExtracted` check to guard against cases where a previously extracted
  167. // module would be extracted twice. Happens when a module is a dependency of an initial and a non-initial
  168. // chunk. See issue #604
  169. if (shouldExtract && !wasExtracted) {
  170. module[`${NS}/extract`] = shouldExtract; // eslint-disable-line no-path-concat
  171. compilation.rebuildModule(module, function (err) {
  172. if (err) {
  173. compilation.errors.push(err);
  174. return callback();
  175. }
  176. meta = module[NS];
  177. // Error out if content is not an array and is not null
  178. if (!Array.isArray(meta.content) && meta.content != null) {
  179. err = new Error(`${module.identifier()} doesn't export content`);
  180. compilation.errors.push(err);
  181. return callback();
  182. }
  183. if (meta.content) {
  184. extractCompilation.addResultToChunk(module.identifier(), meta.content, module, extractedChunk);
  185. }
  186. callback();
  187. });
  188. } else {
  189. if (meta.content) {
  190. extractCompilation.addResultToChunk(module.identifier(), meta.content, module, extractedChunk);
  191. }
  192. callback();
  193. }
  194. } else callback();
  195. }, function (err) {
  196. if (err) return callback(err);
  197. callback();
  198. });
  199. }, function (err) {
  200. if (err) return callback(err);
  201. extractedChunks.forEach(function (extractedChunk) {
  202. if ((0, _helpers.isInitialOrHasNoParents)(extractedChunk)) {
  203. _this3.mergeNonInitialChunks(extractedChunk);
  204. }
  205. }, _this3);
  206. extractedChunks.forEach(function (extractedChunk) {
  207. if (!(0, _helpers.isInitialOrHasNoParents)(extractedChunk)) {
  208. extractedChunk.forEachModule(function (module) {
  209. extractedChunk.removeModule(module);
  210. });
  211. }
  212. });
  213. compilation.applyPlugins('optimize-extracted-chunks', extractedChunks);
  214. callback();
  215. });
  216. });
  217. compilation.plugin('additional-assets', function (callback) {
  218. extractedChunks.forEach(function (extractedChunk) {
  219. if (extractedChunk.getNumberOfModules()) {
  220. extractedChunk.sortModules(function (a, b) {
  221. if (!options.ignoreOrder && (0, _helpers.isInvalidOrder)(a, b)) {
  222. compilation.errors.push(new _OrderUndefinedError2.default(a.getOriginalModule()));
  223. compilation.errors.push(new _OrderUndefinedError2.default(b.getOriginalModule()));
  224. }
  225. return (0, _helpers.getOrder)(a, b);
  226. });
  227. var chunk = extractedChunk.originalChunk;
  228. var source = _this3.renderExtractedChunk(extractedChunk);
  229. var getPath = function getPath(format) {
  230. return compilation.getPath(format, {
  231. chunk
  232. }).replace(/\[(?:(\w+):)?contenthash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, function () {
  233. // eslint-disable-line func-names
  234. return _loaderUtils2.default.getHashDigest(source.source(), arguments[1], arguments[2], parseInt(arguments[3], 10));
  235. });
  236. };
  237. var file = (0, _helpers.isFunction)(filename) ? filename(getPath) : getPath(filename);
  238. compilation.assets[file] = source;
  239. chunk.files.push(file);
  240. }
  241. }, _this3);
  242. callback();
  243. });
  244. });
  245. }
  246. }], [{
  247. key: 'loader',
  248. value: function loader(options) {
  249. return { loader: require.resolve('./loader'), options };
  250. }
  251. }]);
  252. return ExtractTextPlugin;
  253. }();
  254. ExtractTextPlugin.extract = ExtractTextPlugin.prototype.extract.bind(ExtractTextPlugin);
  255. exports.default = ExtractTextPlugin;