utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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.getPreRequester = getPreRequester;
  10. exports.getImportCode = getImportCode;
  11. exports.getModuleCode = getModuleCode;
  12. exports.getExportCode = getExportCode;
  13. exports.shouldUseModulesPlugins = shouldUseModulesPlugins;
  14. var _path = _interopRequireDefault(require("path"));
  15. var _loaderUtils = require("loader-utils");
  16. var _normalizePath = _interopRequireDefault(require("normalize-path"));
  17. var _cssesc = _interopRequireDefault(require("cssesc"));
  18. var _postcssModulesValues = _interopRequireDefault(require("postcss-modules-values"));
  19. var _postcssModulesLocalByDefault = _interopRequireDefault(require("postcss-modules-local-by-default"));
  20. var _postcssModulesExtractImports = _interopRequireDefault(require("postcss-modules-extract-imports"));
  21. var _postcssModulesScope = _interopRequireDefault(require("postcss-modules-scope"));
  22. var _camelcase = _interopRequireDefault(require("camelcase"));
  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)((0, _loaderUtils.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 shouldUseModulesPlugins(modules, resourcePath) {
  79. if (typeof modules === 'undefined') {
  80. return false;
  81. }
  82. if (typeof modules === 'boolean') {
  83. return modules;
  84. }
  85. if (typeof modules === 'string') {
  86. return true;
  87. }
  88. if (typeof modules.auto === 'boolean') {
  89. return modules.auto ? /\.module\.\w+$/i.test(resourcePath) : false;
  90. }
  91. if (modules.auto instanceof RegExp) {
  92. return modules.auto.test(resourcePath);
  93. }
  94. if (typeof modules.auto === 'function') {
  95. return modules.auto(resourcePath);
  96. }
  97. return true;
  98. }
  99. function getModulesPlugins(options, loaderContext) {
  100. let modulesOptions = {
  101. mode: 'local',
  102. exportGlobals: false,
  103. localIdentName: '[hash:base64]',
  104. getLocalIdent,
  105. hashPrefix: '',
  106. localIdentRegExp: null
  107. };
  108. if (typeof options.modules === 'boolean' || typeof options.modules === 'string') {
  109. modulesOptions.mode = typeof options.modules === 'string' ? options.modules : 'local';
  110. } else {
  111. modulesOptions = Object.assign({}, modulesOptions, options.modules);
  112. }
  113. if (typeof modulesOptions.mode === 'function') {
  114. modulesOptions.mode = modulesOptions.mode(loaderContext.resourcePath);
  115. }
  116. let plugins = [];
  117. try {
  118. plugins = [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  119. mode: modulesOptions.mode
  120. }), (0, _postcssModulesExtractImports.default)(), (0, _postcssModulesScope.default)({
  121. generateScopedName: function generateScopedName(exportName) {
  122. let localIdent = modulesOptions.getLocalIdent(loaderContext, modulesOptions.localIdentName, exportName, {
  123. context: modulesOptions.context,
  124. hashPrefix: modulesOptions.hashPrefix,
  125. regExp: modulesOptions.localIdentRegExp
  126. });
  127. if (!localIdent) {
  128. localIdent = getLocalIdent(loaderContext, modulesOptions.localIdentName, exportName, {
  129. context: modulesOptions.context,
  130. hashPrefix: modulesOptions.hashPrefix,
  131. regExp: modulesOptions.localIdentRegExp
  132. });
  133. }
  134. return localIdent;
  135. },
  136. exportGlobals: modulesOptions.exportGlobals
  137. })];
  138. } catch (error) {
  139. loaderContext.emitError(error);
  140. }
  141. return plugins;
  142. }
  143. function normalizeSourceMap(map) {
  144. let newMap = map; // Some loader emit source map as string
  145. // Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
  146. if (typeof newMap === 'string') {
  147. newMap = JSON.parse(newMap);
  148. } // Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
  149. // We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
  150. if (newMap.file) {
  151. newMap.file = (0, _normalizePath.default)(newMap.file);
  152. }
  153. if (newMap.sourceRoot) {
  154. newMap.sourceRoot = (0, _normalizePath.default)(newMap.sourceRoot);
  155. }
  156. if (newMap.sources) {
  157. newMap.sources = newMap.sources.map(source => (0, _normalizePath.default)(source));
  158. }
  159. return newMap;
  160. }
  161. function getPreRequester({
  162. loaders,
  163. loaderIndex
  164. }) {
  165. const cache = Object.create(null);
  166. return number => {
  167. if (cache[number]) {
  168. return cache[number];
  169. }
  170. if (number === false) {
  171. cache[number] = '';
  172. } else {
  173. const loadersRequest = loaders.slice(loaderIndex, loaderIndex + 1 + (typeof number !== 'number' ? 0 : number)).map(x => x.request).join('!');
  174. cache[number] = `-!${loadersRequest}!`;
  175. }
  176. return cache[number];
  177. };
  178. }
  179. function getImportCode(loaderContext, exportType, imports, esModule) {
  180. let code = '';
  181. if (exportType === 'full') {
  182. const apiUrl = (0, _loaderUtils.stringifyRequest)(loaderContext, require.resolve('./runtime/api'));
  183. code += esModule ? `import ___CSS_LOADER_API_IMPORT___ from ${apiUrl};\n` : `var ___CSS_LOADER_API_IMPORT___ = require(${apiUrl});\n`;
  184. }
  185. for (const item of imports) {
  186. const {
  187. importName,
  188. url
  189. } = item;
  190. code += esModule ? `import ${importName} from ${url};\n` : `var ${importName} = require(${url});\n`;
  191. }
  192. return code ? `// Imports\n${code}` : '';
  193. }
  194. function getModuleCode(result, exportType, sourceMap, apiImports, urlReplacements, icssReplacements, esModule) {
  195. if (exportType !== 'full') {
  196. return '';
  197. }
  198. const {
  199. css,
  200. map
  201. } = result;
  202. const sourceMapValue = sourceMap && map ? `,${map}` : '';
  203. let code = JSON.stringify(css);
  204. let beforeCode = '';
  205. beforeCode += esModule ? `var exports = ___CSS_LOADER_API_IMPORT___(${sourceMap});\n` : `exports = ___CSS_LOADER_API_IMPORT___(${sourceMap});\n`;
  206. for (const item of apiImports) {
  207. const {
  208. type,
  209. media,
  210. dedupe
  211. } = item;
  212. beforeCode += type === 'internal' ? `exports.i(${item.importName}${media ? `, ${JSON.stringify(media)}` : dedupe ? ', ""' : ''}${dedupe ? ', true' : ''});\n` : `exports.push([module.id, ${JSON.stringify(`@import url(${item.url});`)}${media ? `, ${JSON.stringify(media)}` : ''}]);\n`;
  213. }
  214. for (const item of urlReplacements) {
  215. const {
  216. replacementName,
  217. importName,
  218. hash,
  219. needQuotes
  220. } = item;
  221. const getUrlOptions = [].concat(hash ? [`hash: ${JSON.stringify(hash)}`] : []).concat(needQuotes ? 'needQuotes: true' : []);
  222. const preparedOptions = getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(', ')} }` : '';
  223. beforeCode += `var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});\n`;
  224. code = code.replace(new RegExp(replacementName, 'g'), () => `" + ${replacementName} + "`);
  225. }
  226. for (const replacement of icssReplacements) {
  227. const {
  228. replacementName,
  229. importName,
  230. localName
  231. } = replacement;
  232. code = code.replace(new RegExp(replacementName, 'g'), () => `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
  233. }
  234. return `${beforeCode}// Module\nexports.push([module.id, ${code}, ""${sourceMapValue}]);\n`;
  235. }
  236. function dashesCamelCase(str) {
  237. return str.replace(/-+(\w)/g, (match, firstLetter) => firstLetter.toUpperCase());
  238. }
  239. function getExportCode(exports, exportType, localsConvention, icssReplacements, esModule) {
  240. let code = '';
  241. let localsCode = '';
  242. const addExportToLocalsCode = (name, value) => {
  243. if (localsCode) {
  244. localsCode += `,\n`;
  245. }
  246. localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
  247. };
  248. for (const {
  249. name,
  250. value
  251. } of exports) {
  252. switch (localsConvention) {
  253. case 'camelCase':
  254. {
  255. addExportToLocalsCode(name, value);
  256. const modifiedName = (0, _camelcase.default)(name);
  257. if (modifiedName !== name) {
  258. addExportToLocalsCode(modifiedName, value);
  259. }
  260. break;
  261. }
  262. case 'camelCaseOnly':
  263. {
  264. addExportToLocalsCode((0, _camelcase.default)(name), value);
  265. break;
  266. }
  267. case 'dashes':
  268. {
  269. addExportToLocalsCode(name, value);
  270. const modifiedName = dashesCamelCase(name);
  271. if (modifiedName !== name) {
  272. addExportToLocalsCode(modifiedName, value);
  273. }
  274. break;
  275. }
  276. case 'dashesOnly':
  277. {
  278. addExportToLocalsCode(dashesCamelCase(name), value);
  279. break;
  280. }
  281. case 'asIs':
  282. default:
  283. addExportToLocalsCode(name, value);
  284. break;
  285. }
  286. }
  287. for (const replacement of icssReplacements) {
  288. const {
  289. replacementName,
  290. importName,
  291. localName
  292. } = replacement;
  293. localsCode = localsCode.replace(new RegExp(replacementName, 'g'), () => exportType === 'locals' ? `" + ${importName}[${JSON.stringify(localName)}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
  294. }
  295. if (exportType === 'locals') {
  296. code += `${esModule ? 'export default' : 'module.exports ='} ${localsCode ? `{\n${localsCode}\n}` : '{}'};\n`;
  297. } else {
  298. if (localsCode) {
  299. code += `exports.locals = {\n${localsCode}\n};\n`;
  300. }
  301. code += `${esModule ? 'export default' : 'module.exports ='} exports;\n`;
  302. }
  303. return `// Exports\n${code}`;
  304. }