utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.normalizeUrl = normalizeUrl;
  6. exports.getFilter = getFilter;
  7. exports.getModulesPlugins = getModulesPlugins;
  8. exports.normalizeSourceMap = normalizeSourceMap;
  9. exports.getImportCode = getImportCode;
  10. exports.getModuleCode = getModuleCode;
  11. exports.getExportCode = getExportCode;
  12. var _path = _interopRequireDefault(require("path"));
  13. var _loaderUtils = _interopRequireWildcard(require("loader-utils"));
  14. var _normalizePath = _interopRequireDefault(require("normalize-path"));
  15. var _cssesc = _interopRequireDefault(require("cssesc"));
  16. var _postcssModulesValues = _interopRequireDefault(require("postcss-modules-values"));
  17. var _postcssModulesLocalByDefault = _interopRequireDefault(require("postcss-modules-local-by-default"));
  18. var _postcssModulesExtractImports = _interopRequireDefault(require("postcss-modules-extract-imports"));
  19. var _postcssModulesScope = _interopRequireDefault(require("postcss-modules-scope"));
  20. var _camelcase = _interopRequireDefault(require("camelcase"));
  21. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  22. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }
  23. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24. /*
  25. MIT License http://www.opensource.org/licenses/mit-license.php
  26. Author Tobias Koppers @sokra
  27. */
  28. const whitespace = '[\\x20\\t\\r\\n\\f]';
  29. const unescapeRegExp = new RegExp(`\\\\([\\da-f]{1,6}${whitespace}?|(${whitespace})|.)`, 'ig');
  30. function unescape(str) {
  31. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  32. const high = `0x${escaped}` - 0x10000;
  33. /* eslint-disable line-comment-position */
  34. // NaN means non-codepoint
  35. // Workaround erroneous numeric interpretation of +"0x"
  36. // eslint-disable-next-line no-self-compare
  37. return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint
  38. String.fromCharCode(high + 0x10000) : // Supplemental Plane codepoint (surrogate pair)
  39. // eslint-disable-next-line no-bitwise
  40. String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
  41. /* eslint-enable line-comment-position */
  42. });
  43. } // eslint-disable-next-line no-control-regex
  44. const filenameReservedRegex = /[<>:"/\\|?*\x00-\x1F]/g; // eslint-disable-next-line no-control-regex
  45. const reControlChars = /[\u0000-\u001f\u0080-\u009f]/g;
  46. const reRelativePath = /^\.+/;
  47. function getLocalIdent(loaderContext, localIdentName, localName, options) {
  48. if (!options.context) {
  49. // eslint-disable-next-line no-param-reassign
  50. options.context = loaderContext.rootContext;
  51. }
  52. const request = (0, _normalizePath.default)(_path.default.relative(options.context || '', loaderContext.resourcePath)); // eslint-disable-next-line no-param-reassign
  53. options.content = `${options.hashPrefix + request}+${unescape(localName)}`; // Using `[path]` placeholder outputs `/` we need escape their
  54. // Also directories can contains invalid characters for css we need escape their too
  55. return (0, _cssesc.default)(_loaderUtils.default.interpolateName(loaderContext, localIdentName, options) // For `[hash]` placeholder
  56. .replace(/^((-?[0-9])|--)/, '_$1').replace(filenameReservedRegex, '-').replace(reControlChars, '-').replace(reRelativePath, '-').replace(/\./g, '-'), {
  57. isIdentifier: true
  58. }).replace(/\\\[local\\\]/gi, localName);
  59. }
  60. function normalizeUrl(url, isStringValue) {
  61. let normalizedUrl = url;
  62. if (isStringValue && /\\[\n]/.test(normalizedUrl)) {
  63. normalizedUrl = normalizedUrl.replace(/\\[\n]/g, '');
  64. }
  65. return (0, _loaderUtils.urlToRequest)(decodeURIComponent(unescape(normalizedUrl)));
  66. }
  67. function getFilter(filter, resourcePath, defaultFilter = null) {
  68. return item => {
  69. if (defaultFilter && !defaultFilter(item)) {
  70. return false;
  71. }
  72. if (typeof filter === 'function') {
  73. return filter(item, resourcePath);
  74. }
  75. return true;
  76. };
  77. }
  78. function getModulesPlugins(options, loaderContext) {
  79. let modulesOptions = {
  80. mode: 'local',
  81. localIdentName: '[hash:base64]',
  82. getLocalIdent,
  83. hashPrefix: '',
  84. localIdentRegExp: null
  85. };
  86. if (typeof options.modules === 'boolean' || typeof options.modules === 'string') {
  87. modulesOptions.mode = typeof options.modules === 'string' ? options.modules : 'local';
  88. } else {
  89. modulesOptions = Object.assign({}, modulesOptions, options.modules);
  90. }
  91. return [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  92. mode: modulesOptions.mode
  93. }), (0, _postcssModulesExtractImports.default)(), (0, _postcssModulesScope.default)({
  94. generateScopedName: function generateScopedName(exportName) {
  95. let localIdent = modulesOptions.getLocalIdent(loaderContext, modulesOptions.localIdentName, exportName, {
  96. context: modulesOptions.context,
  97. hashPrefix: modulesOptions.hashPrefix,
  98. regExp: modulesOptions.localIdentRegExp
  99. });
  100. if (!localIdent) {
  101. localIdent = getLocalIdent(loaderContext, modulesOptions.localIdentName, exportName, {
  102. context: modulesOptions.context,
  103. hashPrefix: modulesOptions.hashPrefix,
  104. regExp: modulesOptions.localIdentRegExp
  105. });
  106. }
  107. return localIdent;
  108. }
  109. })];
  110. }
  111. function normalizeSourceMap(map) {
  112. let newMap = map; // Some loader emit source map as string
  113. // Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
  114. if (typeof newMap === 'string') {
  115. newMap = JSON.parse(newMap);
  116. } // Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
  117. // We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
  118. if (newMap.file) {
  119. newMap.file = (0, _normalizePath.default)(newMap.file);
  120. }
  121. if (newMap.sourceRoot) {
  122. newMap.sourceRoot = (0, _normalizePath.default)(newMap.sourceRoot);
  123. }
  124. if (newMap.sources) {
  125. newMap.sources = newMap.sources.map(source => (0, _normalizePath.default)(source));
  126. }
  127. return newMap;
  128. }
  129. function getImportPrefix(loaderContext, importLoaders) {
  130. if (importLoaders === false) {
  131. return '';
  132. }
  133. const numberImportedLoaders = parseInt(importLoaders, 10) || 0;
  134. const loadersRequest = loaderContext.loaders.slice(loaderContext.loaderIndex, loaderContext.loaderIndex + 1 + numberImportedLoaders).map(x => x.request).join('!');
  135. return `-!${loadersRequest}!`;
  136. }
  137. function getImportCode(loaderContext, imports, exportType, sourceMap, importLoaders, esModule) {
  138. const importItems = [];
  139. const codeItems = [];
  140. const atRuleImportNames = new Map();
  141. const urlImportNames = new Map();
  142. let importPrefix;
  143. if (exportType === 'full') {
  144. importItems.push(esModule ? `import ___CSS_LOADER_API_IMPORT___ from ${(0, _loaderUtils.stringifyRequest)(loaderContext, require.resolve('./runtime/api'))};` : `var ___CSS_LOADER_API_IMPORT___ = require(${(0, _loaderUtils.stringifyRequest)(loaderContext, require.resolve('./runtime/api'))});`);
  145. codeItems.push(esModule ? `var exports = ___CSS_LOADER_API_IMPORT___(${sourceMap});` : `exports = ___CSS_LOADER_API_IMPORT___(${sourceMap});`);
  146. }
  147. imports.forEach(item => {
  148. // eslint-disable-next-line default-case
  149. switch (item.type) {
  150. case '@import':
  151. {
  152. const {
  153. url,
  154. media
  155. } = item;
  156. const preparedMedia = media ? `, ${JSON.stringify(media)}` : '';
  157. if (!(0, _loaderUtils.isUrlRequest)(url)) {
  158. codeItems.push(`exports.push([module.id, ${JSON.stringify(`@import url(${url});`)}${preparedMedia}]);`);
  159. return;
  160. }
  161. let importName = atRuleImportNames.get(url);
  162. if (!importName) {
  163. if (!importPrefix) {
  164. importPrefix = getImportPrefix(loaderContext, importLoaders);
  165. }
  166. importName = `___CSS_LOADER_AT_RULE_IMPORT_${atRuleImportNames.size}___`;
  167. importItems.push(esModule ? `import ${importName} from ${(0, _loaderUtils.stringifyRequest)(loaderContext, importPrefix + url)};` : `var ${importName} = require(${(0, _loaderUtils.stringifyRequest)(loaderContext, importPrefix + url)});`);
  168. atRuleImportNames.set(url, importName);
  169. }
  170. codeItems.push(`exports.i(${importName}${preparedMedia});`);
  171. }
  172. break;
  173. case 'url':
  174. {
  175. if (urlImportNames.size === 0) {
  176. importItems.push(esModule ? `import ___CSS_LOADER_GET_URL_IMPORT___ from ${(0, _loaderUtils.stringifyRequest)(loaderContext, require.resolve('./runtime/getUrl.js'))};` : `var ___CSS_LOADER_GET_URL_IMPORT___ = require(${(0, _loaderUtils.stringifyRequest)(loaderContext, require.resolve('./runtime/getUrl.js'))});`);
  177. }
  178. const {
  179. replacementName,
  180. url,
  181. hash,
  182. needQuotes
  183. } = item;
  184. let importName = urlImportNames.get(url);
  185. if (!importName) {
  186. importName = `___CSS_LOADER_URL_IMPORT_${urlImportNames.size}___`;
  187. importItems.push(esModule ? `import ${importName} from ${(0, _loaderUtils.stringifyRequest)(loaderContext, url)};` : `var ${importName} = require(${(0, _loaderUtils.stringifyRequest)(loaderContext, url)});`);
  188. urlImportNames.set(url, importName);
  189. }
  190. const getUrlOptions = [].concat(hash ? [`hash: ${JSON.stringify(hash)}`] : []).concat(needQuotes ? 'needQuotes: true' : []);
  191. const preparedOptions = getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(', ')} }` : '';
  192. codeItems.push(`var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});`);
  193. }
  194. break;
  195. case 'icss-import':
  196. {
  197. const {
  198. importName,
  199. url,
  200. media
  201. } = item;
  202. const preparedMedia = media ? `, ${JSON.stringify(media)}` : ', ""';
  203. if (!importPrefix) {
  204. importPrefix = getImportPrefix(loaderContext, importLoaders);
  205. }
  206. importItems.push(esModule ? `import ${importName} from ${(0, _loaderUtils.stringifyRequest)(loaderContext, importPrefix + url)};` : `var ${importName} = require(${(0, _loaderUtils.stringifyRequest)(loaderContext, importPrefix + url)});`);
  207. if (exportType === 'full') {
  208. codeItems.push(`exports.i(${importName}${preparedMedia}, true);`);
  209. }
  210. }
  211. break;
  212. }
  213. });
  214. const items = importItems.concat(codeItems);
  215. return items.length > 0 ? `// Imports\n${items.join('\n')}\n` : '';
  216. }
  217. function getModuleCode(loaderContext, result, exportType, sourceMap, replacers) {
  218. if (exportType !== 'full') {
  219. return '';
  220. }
  221. const {
  222. css,
  223. map
  224. } = result;
  225. const sourceMapValue = sourceMap && map ? `,${map}` : '';
  226. let cssCode = JSON.stringify(css);
  227. replacers.forEach(replacer => {
  228. const {
  229. type,
  230. replacementName
  231. } = replacer;
  232. if (type === 'url') {
  233. cssCode = cssCode.replace(new RegExp(replacementName, 'g'), () => `" + ${replacementName} + "`);
  234. }
  235. if (type === 'icss-import') {
  236. const {
  237. importName,
  238. localName
  239. } = replacer;
  240. cssCode = cssCode.replace(new RegExp(replacementName, 'g'), () => `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
  241. }
  242. });
  243. return `// Module\nexports.push([module.id, ${cssCode}, ""${sourceMapValue}]);\n`;
  244. }
  245. function dashesCamelCase(str) {
  246. return str.replace(/-+(\w)/g, (match, firstLetter) => firstLetter.toUpperCase());
  247. }
  248. function getExportCode(loaderContext, exports, exportType, replacers, localsConvention, esModule) {
  249. const exportItems = [];
  250. let exportLocalsCode;
  251. if (exports.length > 0) {
  252. const exportLocals = [];
  253. const addExportedLocal = (name, value) => {
  254. exportLocals.push(`\t${JSON.stringify(name)}: ${JSON.stringify(value)}`);
  255. };
  256. exports.forEach(item => {
  257. const {
  258. name,
  259. value
  260. } = item;
  261. switch (localsConvention) {
  262. case 'camelCase':
  263. {
  264. addExportedLocal(name, value);
  265. const modifiedName = (0, _camelcase.default)(name);
  266. if (modifiedName !== name) {
  267. addExportedLocal(modifiedName, value);
  268. }
  269. break;
  270. }
  271. case 'camelCaseOnly':
  272. {
  273. addExportedLocal((0, _camelcase.default)(name), value);
  274. break;
  275. }
  276. case 'dashes':
  277. {
  278. addExportedLocal(name, value);
  279. const modifiedName = dashesCamelCase(name);
  280. if (modifiedName !== name) {
  281. addExportedLocal(modifiedName, value);
  282. }
  283. break;
  284. }
  285. case 'dashesOnly':
  286. {
  287. addExportedLocal(dashesCamelCase(name), value);
  288. break;
  289. }
  290. case 'asIs':
  291. default:
  292. addExportedLocal(name, value);
  293. break;
  294. }
  295. });
  296. exportLocalsCode = exportLocals.join(',\n');
  297. replacers.forEach(replacer => {
  298. if (replacer.type === 'icss-import') {
  299. const {
  300. replacementName,
  301. importName,
  302. localName
  303. } = replacer;
  304. exportLocalsCode = exportLocalsCode.replace(new RegExp(replacementName, 'g'), () => exportType === 'locals' ? `" + ${importName}[${JSON.stringify(localName)}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
  305. }
  306. });
  307. }
  308. if (exportType === 'locals') {
  309. exportItems.push(`${esModule ? 'export default' : 'module.exports ='} ${exportLocalsCode ? `{\n${exportLocalsCode}\n}` : '{}'};`);
  310. } else {
  311. if (exportLocalsCode) {
  312. exportItems.push(`exports.locals = {\n${exportLocalsCode}\n};`);
  313. }
  314. exportItems.push(`${esModule ? 'export default' : 'module.exports ='} exports;`);
  315. }
  316. return `// Exports\n${exportItems.join('\n')}\n`;
  317. }