utils.js 18 KB

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