utils.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.getRenderFunctionFromSassImplementation = getRenderFunctionFromSassImplementation;
  6. exports.getSassImplementation = getSassImplementation;
  7. exports.getSassOptions = getSassOptions;
  8. exports.getWebpackImporter = getWebpackImporter;
  9. exports.getWebpackResolver = getWebpackResolver;
  10. exports.isSupportedFibers = isSupportedFibers;
  11. exports.normalizeSourceMap = normalizeSourceMap;
  12. var _url = _interopRequireDefault(require("url"));
  13. var _path = _interopRequireDefault(require("path"));
  14. var _semver = _interopRequireDefault(require("semver"));
  15. var _full = require("klona/full");
  16. var _loaderUtils = require("loader-utils");
  17. var _neoAsync = _interopRequireDefault(require("neo-async"));
  18. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  19. function getDefaultSassImplementation() {
  20. let sassImplPkg = "sass";
  21. try {
  22. require.resolve("sass");
  23. } catch (error) {
  24. try {
  25. require.resolve("node-sass");
  26. sassImplPkg = "node-sass";
  27. } catch (ignoreError) {
  28. sassImplPkg = "sass";
  29. }
  30. } // eslint-disable-next-line import/no-dynamic-require, global-require
  31. return require(sassImplPkg);
  32. }
  33. /**
  34. * @public
  35. * This function is not Webpack-specific and can be used by tools wishing to
  36. * mimic `sass-loader`'s behaviour, so its signature should not be changed.
  37. */
  38. function getSassImplementation(loaderContext, implementation) {
  39. let resolvedImplementation = implementation;
  40. if (!resolvedImplementation) {
  41. try {
  42. resolvedImplementation = getDefaultSassImplementation();
  43. } catch (error) {
  44. loaderContext.emitError(error);
  45. return;
  46. }
  47. }
  48. const {
  49. info
  50. } = resolvedImplementation;
  51. if (!info) {
  52. loaderContext.emitError(new Error("Unknown Sass implementation."));
  53. return;
  54. }
  55. const infoParts = info.split("\t");
  56. if (infoParts.length < 2) {
  57. loaderContext.emitError(new Error(`Unknown Sass implementation "${info}".`));
  58. return;
  59. }
  60. const [implementationName, version] = infoParts;
  61. if (implementationName === "dart-sass") {
  62. if (!_semver.default.satisfies(version, "^1.3.0")) {
  63. loaderContext.emitError(new Error(`Dart Sass version ${version} is incompatible with ^1.3.0.`));
  64. } // eslint-disable-next-line consistent-return
  65. return resolvedImplementation;
  66. } else if (implementationName === "node-sass") {
  67. if (!_semver.default.satisfies(version, "^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0")) {
  68. loaderContext.emitError(new Error(`Node Sass version ${version} is incompatible with ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0.`));
  69. } // eslint-disable-next-line consistent-return
  70. return resolvedImplementation;
  71. }
  72. loaderContext.emitError(new Error(`Unknown Sass implementation "${implementationName}".`));
  73. }
  74. function isSupportedFibers() {
  75. const [nodeVersion] = process.versions.node.split(".");
  76. return Number(nodeVersion) < 16;
  77. }
  78. function isProductionLikeMode(loaderContext) {
  79. return loaderContext.mode === "production" || !loaderContext.mode;
  80. }
  81. function proxyCustomImporters(importers, loaderContext) {
  82. return [].concat(importers).map(importer => function proxyImporter(...args) {
  83. this.webpackLoaderContext = loaderContext;
  84. return importer.apply(this, args);
  85. });
  86. }
  87. /**
  88. * Derives the sass options from the loader context and normalizes its values with sane defaults.
  89. *
  90. * @param {object} loaderContext
  91. * @param {object} loaderOptions
  92. * @param {string} content
  93. * @param {object} implementation
  94. * @param {boolean} useSourceMap
  95. * @returns {Object}
  96. */
  97. async function getSassOptions(loaderContext, loaderOptions, content, implementation, useSourceMap) {
  98. const options = (0, _full.klona)(loaderOptions.sassOptions ? typeof loaderOptions.sassOptions === "function" ? loaderOptions.sassOptions(loaderContext) || {} : loaderOptions.sassOptions : {});
  99. const isDartSass = implementation.info.includes("dart-sass");
  100. if (isDartSass && isSupportedFibers()) {
  101. const shouldTryToResolveFibers = !options.fiber && options.fiber !== false;
  102. if (shouldTryToResolveFibers) {
  103. let fibers;
  104. try {
  105. fibers = require.resolve("fibers");
  106. } catch (_error) {// Nothing
  107. }
  108. if (fibers) {
  109. // eslint-disable-next-line global-require, import/no-dynamic-require
  110. options.fiber = require(fibers);
  111. }
  112. } else if (options.fiber === false) {
  113. // Don't pass the `fiber` option for `sass` (`Dart Sass`)
  114. delete options.fiber;
  115. }
  116. } else {
  117. // Don't pass the `fiber` option for `node-sass`
  118. delete options.fiber;
  119. }
  120. options.file = loaderContext.resourcePath;
  121. options.data = loaderOptions.additionalData ? typeof loaderOptions.additionalData === "function" ? await loaderOptions.additionalData(content, loaderContext) : `${loaderOptions.additionalData}\n${content}` : content; // opt.outputStyle
  122. if (!options.outputStyle && isProductionLikeMode(loaderContext)) {
  123. options.outputStyle = "compressed";
  124. }
  125. if (useSourceMap) {
  126. // Deliberately overriding the sourceMap option here.
  127. // node-sass won't produce source maps if the data option is used and options.sourceMap is not a string.
  128. // In case it is a string, options.sourceMap should be a path where the source map is written.
  129. // But since we're using the data option, the source map will not actually be written, but
  130. // all paths in sourceMap.sources will be relative to that path.
  131. // Pretty complicated... :(
  132. options.sourceMap = true;
  133. options.outFile = _path.default.join(loaderContext.rootContext, "style.css.map");
  134. options.sourceMapContents = true;
  135. options.omitSourceMapUrl = true;
  136. options.sourceMapEmbed = false;
  137. }
  138. const {
  139. resourcePath
  140. } = loaderContext;
  141. const ext = _path.default.extname(resourcePath); // If we are compiling sass and indentedSyntax isn't set, automatically set it.
  142. if (ext && ext.toLowerCase() === ".sass" && typeof options.indentedSyntax === "undefined") {
  143. options.indentedSyntax = true;
  144. } else {
  145. options.indentedSyntax = Boolean(options.indentedSyntax);
  146. } // Allow passing custom importers to `sass`/`node-sass`. Accepts `Function` or an array of `Function`s.
  147. options.importer = options.importer ? proxyCustomImporters(Array.isArray(options.importer) ? options.importer : [options.importer], loaderContext) : [];
  148. options.includePaths = [].concat(process.cwd()).concat( // We use `includePaths` in context for resolver, so it should be always absolute
  149. (options.includePaths || []).map(includePath => _path.default.isAbsolute(includePath) ? includePath : _path.default.join(process.cwd(), includePath))).concat(process.env.SASS_PATH ? process.env.SASS_PATH.split(process.platform === "win32" ? ";" : ":") : []);
  150. return options;
  151. } // Examples:
  152. // - ~package
  153. // - ~package/
  154. // - ~@org
  155. // - ~@org/
  156. // - ~@org/package
  157. // - ~@org/package/
  158. const isModuleImport = /^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/]+\/)$/;
  159. /**
  160. * When `sass`/`node-sass` tries to resolve an import, it uses a special algorithm.
  161. * Since the `sass-loader` uses webpack to resolve the modules, we need to simulate that algorithm.
  162. * This function returns an array of import paths to try.
  163. * The last entry in the array is always the original url to enable straight-forward webpack.config aliases.
  164. *
  165. * We don't need emulate `dart-sass` "It's not clear which file to import." errors (when "file.ext" and "_file.ext" files are present simultaneously in the same directory).
  166. * This reduces performance and `dart-sass` always do it on own side.
  167. *
  168. * @param {string} url
  169. * @param {boolean} forWebpackResolver
  170. * @param {string} rootContext
  171. * @returns {Array<string>}
  172. */
  173. function getPossibleRequests( // eslint-disable-next-line no-shadow
  174. url, forWebpackResolver = false, rootContext = false) {
  175. const request = (0, _loaderUtils.urlToRequest)(url, // Maybe it is server-relative URLs
  176. forWebpackResolver && rootContext); // In case there is module request, send this to webpack resolver
  177. if (forWebpackResolver && isModuleImport.test(url)) {
  178. return [...new Set([request, url])];
  179. } // Keep in mind: ext can also be something like '.datepicker' when the true extension is omitted and the filename contains a dot.
  180. // @see https://github.com/webpack-contrib/sass-loader/issues/167
  181. const ext = _path.default.extname(request).toLowerCase(); // Because @import is also defined in CSS, Sass needs a way of compiling plain CSS @imports without trying to import the files at compile time.
  182. // To accomplish this, and to ensure SCSS is as much of a superset of CSS as possible, Sass will compile any @imports with the following characteristics to plain CSS imports:
  183. // - imports where the URL ends with .css.
  184. // - imports where the URL begins http:// or https://.
  185. // - imports where the URL is written as a url().
  186. // - imports that have media queries.
  187. //
  188. // The `node-sass` package sends `@import` ending on `.css` to importer, it is bug, so we skip resolve
  189. if (ext === ".css") {
  190. return [];
  191. }
  192. const dirname = _path.default.dirname(request);
  193. const basename = _path.default.basename(request);
  194. return [...new Set([`${dirname}/_${basename}`, request].concat(forWebpackResolver ? [`${_path.default.dirname(url)}/_${basename}`, url] : []))];
  195. }
  196. function promiseResolve(callbackResolve) {
  197. return (context, request) => new Promise((resolve, reject) => {
  198. callbackResolve(context, request, (error, result) => {
  199. if (error) {
  200. reject(error);
  201. } else {
  202. resolve(result);
  203. }
  204. });
  205. });
  206. }
  207. const IS_SPECIAL_MODULE_IMPORT = /^~[^/]+$/; // `[drive_letter]:\` + `\\[server]\[sharename]\`
  208. const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
  209. /**
  210. * @public
  211. * Create the resolve function used in the custom Sass importer.
  212. *
  213. * Can be used by external tools to mimic how `sass-loader` works, for example
  214. * in a Jest transform. Such usages will want to wrap `resolve.create` from
  215. * [`enhanced-resolve`]{@link https://github.com/webpack/enhanced-resolve} to
  216. * pass as the `resolverFactory` argument.
  217. *
  218. * @param {Function} resolverFactory - A factory function for creating a Webpack
  219. * resolver.
  220. * @param {Object} implementation - The imported Sass implementation, both
  221. * `sass` (Dart Sass) and `node-sass` are supported.
  222. * @param {string[]} [includePaths] - The list of include paths passed to Sass.
  223. * @param {boolean} [rootContext] - The configured Webpack root context.
  224. *
  225. * @throws If a compatible Sass implementation cannot be found.
  226. */
  227. function getWebpackResolver(resolverFactory, implementation, includePaths = [], rootContext = false) {
  228. async function startResolving(resolutionMap) {
  229. if (resolutionMap.length === 0) {
  230. return Promise.reject();
  231. }
  232. const [{
  233. possibleRequests
  234. }] = resolutionMap;
  235. if (possibleRequests.length === 0) {
  236. return Promise.reject();
  237. }
  238. const [{
  239. resolve,
  240. context
  241. }] = resolutionMap;
  242. try {
  243. return await resolve(context, possibleRequests[0]);
  244. } catch (_ignoreError) {
  245. const [, ...tailResult] = possibleRequests;
  246. if (tailResult.length === 0) {
  247. const [, ...tailResolutionMap] = resolutionMap;
  248. return startResolving(tailResolutionMap);
  249. } // eslint-disable-next-line no-param-reassign
  250. resolutionMap[0].possibleRequests = tailResult;
  251. return startResolving(resolutionMap);
  252. }
  253. }
  254. const isDartSass = implementation.info.includes("dart-sass");
  255. const sassResolve = promiseResolve(resolverFactory({
  256. alias: [],
  257. aliasFields: [],
  258. conditionNames: [],
  259. descriptionFiles: [],
  260. extensions: [".sass", ".scss", ".css"],
  261. exportsFields: [],
  262. mainFields: [],
  263. mainFiles: ["_index", "index"],
  264. modules: [],
  265. restrictions: [/\.((sa|sc|c)ss)$/i]
  266. }));
  267. const webpackResolve = promiseResolve(resolverFactory({
  268. conditionNames: ["sass", "style"],
  269. mainFields: ["sass", "style", "main", "..."],
  270. mainFiles: ["_index", "index", "..."],
  271. extensions: [".sass", ".scss", ".css"],
  272. restrictions: [/\.((sa|sc|c)ss)$/i]
  273. }));
  274. return (context, request) => {
  275. const originalRequest = request;
  276. const isFileScheme = originalRequest.slice(0, 5).toLowerCase() === "file:";
  277. if (isFileScheme) {
  278. try {
  279. // eslint-disable-next-line no-param-reassign
  280. request = _url.default.fileURLToPath(originalRequest);
  281. } catch (ignoreError) {
  282. // eslint-disable-next-line no-param-reassign
  283. request = request.slice(7);
  284. }
  285. }
  286. let resolutionMap = [];
  287. const needEmulateSassResolver = // `sass` doesn't support module import
  288. !IS_SPECIAL_MODULE_IMPORT.test(request) && // We need improve absolute paths handling.
  289. // Absolute paths should be resolved:
  290. // - Server-relative URLs - `<context>/path/to/file.ext` (where `<context>` is root context)
  291. // - Absolute path - `/full/path/to/file.ext` or `C:\\full\path\to\file.ext`
  292. !isFileScheme && !originalRequest.startsWith("/") && !IS_NATIVE_WIN32_PATH.test(originalRequest);
  293. if (includePaths.length > 0 && needEmulateSassResolver) {
  294. // The order of import precedence is as follows:
  295. //
  296. // 1. Filesystem imports relative to the base file.
  297. // 2. Custom importer imports.
  298. // 3. Filesystem imports relative to the working directory.
  299. // 4. Filesystem imports relative to an `includePaths` path.
  300. // 5. Filesystem imports relative to a `SASS_PATH` path.
  301. //
  302. // Because `sass`/`node-sass` run custom importers before `3`, `4` and `5` points, we need to emulate this behavior to avoid wrong resolution.
  303. const sassPossibleRequests = getPossibleRequests(request); // `node-sass` calls our importer before `1. Filesystem imports relative to the base file.`, so we need emulate this too
  304. if (!isDartSass) {
  305. resolutionMap = resolutionMap.concat({
  306. resolve: sassResolve,
  307. context: _path.default.dirname(context),
  308. possibleRequests: sassPossibleRequests
  309. });
  310. }
  311. resolutionMap = resolutionMap.concat( // eslint-disable-next-line no-shadow
  312. includePaths.map(context => {
  313. return {
  314. resolve: sassResolve,
  315. context,
  316. possibleRequests: sassPossibleRequests
  317. };
  318. }));
  319. }
  320. const webpackPossibleRequests = getPossibleRequests(request, true, rootContext);
  321. resolutionMap = resolutionMap.concat({
  322. resolve: webpackResolve,
  323. context: _path.default.dirname(context),
  324. possibleRequests: webpackPossibleRequests
  325. });
  326. return startResolving(resolutionMap);
  327. };
  328. }
  329. const matchCss = /\.css$/i;
  330. function getWebpackImporter(loaderContext, implementation, includePaths) {
  331. const resolve = getWebpackResolver(loaderContext.getResolve, implementation, includePaths, loaderContext.rootContext);
  332. return (originalUrl, prev, done) => {
  333. resolve(prev, originalUrl).then(result => {
  334. // Add the result as dependency.
  335. // Although we're also using stats.includedFiles, this might come in handy when an error occurs.
  336. // In this case, we don't get stats.includedFiles from node-sass/sass.
  337. loaderContext.addDependency(_path.default.normalize(result)); // By removing the CSS file extension, we trigger node-sass to include the CSS file instead of just linking it.
  338. done({
  339. file: result.replace(matchCss, "")
  340. });
  341. }) // Catch all resolving errors, return the original file and pass responsibility back to other custom importers
  342. .catch(() => {
  343. done({
  344. file: originalUrl
  345. });
  346. });
  347. };
  348. }
  349. let nodeSassJobQueue = null;
  350. /**
  351. * Verifies that the implementation and version of Sass is supported by this loader.
  352. *
  353. * @param {Object} implementation
  354. * @returns {Function}
  355. */
  356. function getRenderFunctionFromSassImplementation(implementation) {
  357. const isDartSass = implementation.info.includes("dart-sass");
  358. if (isDartSass) {
  359. return implementation.render.bind(implementation);
  360. } // There is an issue with node-sass when async custom importers are used
  361. // See https://github.com/sass/node-sass/issues/857#issuecomment-93594360
  362. // We need to use a job queue to make sure that one thread is always available to the UV lib
  363. if (nodeSassJobQueue === null) {
  364. const threadPoolSize = Number(process.env.UV_THREADPOOL_SIZE || 4);
  365. nodeSassJobQueue = _neoAsync.default.queue(implementation.render.bind(implementation), threadPoolSize - 1);
  366. }
  367. return nodeSassJobQueue.push.bind(nodeSassJobQueue);
  368. }
  369. const ABSOLUTE_SCHEME = /^[A-Za-z0-9+\-.]+:/;
  370. function getURLType(source) {
  371. if (source[0] === "/") {
  372. if (source[1] === "/") {
  373. return "scheme-relative";
  374. }
  375. return "path-absolute";
  376. }
  377. if (IS_NATIVE_WIN32_PATH.test(source)) {
  378. return "path-absolute";
  379. }
  380. return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
  381. }
  382. function normalizeSourceMap(map, rootContext) {
  383. const newMap = map; // result.map.file is an optional property that provides the output filename.
  384. // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
  385. // eslint-disable-next-line no-param-reassign
  386. delete newMap.file; // eslint-disable-next-line no-param-reassign
  387. newMap.sourceRoot = ""; // node-sass returns POSIX paths, that's why we need to transform them back to native paths.
  388. // This fixes an error on windows where the source-map module cannot resolve the source maps.
  389. // @see https://github.com/webpack-contrib/sass-loader/issues/366#issuecomment-279460722
  390. // eslint-disable-next-line no-param-reassign
  391. newMap.sources = newMap.sources.map(source => {
  392. const sourceType = getURLType(source); // Do no touch `scheme-relative`, `path-absolute` and `absolute` types
  393. if (sourceType === "path-relative") {
  394. return _path.default.resolve(rootContext, _path.default.normalize(source));
  395. }
  396. return source;
  397. });
  398. return newMap;
  399. }