utils.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.errorFactory = errorFactory;
  6. exports.getCompileFn = getCompileFn;
  7. exports.getModernWebpackImporter = getModernWebpackImporter;
  8. exports.getSassImplementation = getSassImplementation;
  9. exports.getSassOptions = getSassOptions;
  10. exports.getWebpackImporter = getWebpackImporter;
  11. exports.getWebpackResolver = getWebpackResolver;
  12. exports.normalizeSourceMap = normalizeSourceMap;
  13. var _url = _interopRequireDefault(require("url"));
  14. var _path = _interopRequireDefault(require("path"));
  15. function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
  16. function getDefaultSassImplementation() {
  17. let sassImplPkg = "sass";
  18. try {
  19. require.resolve("sass-embedded");
  20. sassImplPkg = "sass-embedded";
  21. } catch (ignoreError) {
  22. try {
  23. require.resolve("sass");
  24. } catch (_ignoreError) {
  25. try {
  26. require.resolve("node-sass");
  27. sassImplPkg = "node-sass";
  28. } catch (__ignoreError) {
  29. sassImplPkg = "sass";
  30. }
  31. }
  32. }
  33. // eslint-disable-next-line import/no-dynamic-require, global-require
  34. return require(sassImplPkg);
  35. }
  36. /**
  37. * This function is not Webpack-specific and can be used by tools wishing to mimic `sass-loader`'s behaviour, so its signature should not be changed.
  38. */
  39. function getSassImplementation(loaderContext, implementation) {
  40. let resolvedImplementation = implementation;
  41. if (!resolvedImplementation) {
  42. resolvedImplementation = getDefaultSassImplementation();
  43. }
  44. if (typeof resolvedImplementation === "string") {
  45. // eslint-disable-next-line import/no-dynamic-require, global-require
  46. resolvedImplementation = require(resolvedImplementation);
  47. }
  48. const {
  49. info
  50. } = resolvedImplementation;
  51. if (!info) {
  52. throw new Error("Unknown Sass implementation.");
  53. }
  54. const infoParts = info.split("\t");
  55. if (infoParts.length < 2) {
  56. throw new Error(`Unknown Sass implementation "${info}".`);
  57. }
  58. const [implementationName] = infoParts;
  59. if (implementationName === "dart-sass") {
  60. // eslint-disable-next-line consistent-return
  61. return resolvedImplementation;
  62. } else if (implementationName === "node-sass") {
  63. // eslint-disable-next-line consistent-return
  64. return resolvedImplementation;
  65. } else if (implementationName === "sass-embedded") {
  66. // eslint-disable-next-line consistent-return
  67. return resolvedImplementation;
  68. }
  69. throw new Error(`Unknown Sass implementation "${implementationName}".`);
  70. }
  71. /**
  72. * @param {any} loaderContext
  73. * @returns {boolean}
  74. */
  75. function isProductionLikeMode(loaderContext) {
  76. return loaderContext.mode === "production" || !loaderContext.mode;
  77. }
  78. function proxyCustomImporters(importers, loaderContext) {
  79. return [].concat(importers).map(importer => function proxyImporter(...args) {
  80. const self = {
  81. ...this,
  82. webpackLoaderContext: loaderContext
  83. };
  84. return importer.apply(self, 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. * @param {"legacy" | "modern" | "modern-compiler"} apiType
  96. * @returns {Object}
  97. */
  98. async function getSassOptions(loaderContext, loaderOptions, content, implementation, useSourceMap, apiType) {
  99. const options = loaderOptions.sassOptions ? typeof loaderOptions.sassOptions === "function" ? loaderOptions.sassOptions(loaderContext) || {} : loaderOptions.sassOptions : {};
  100. const sassOptions = {
  101. ...options,
  102. data: loaderOptions.additionalData ? typeof loaderOptions.additionalData === "function" ? await loaderOptions.additionalData(content, loaderContext) : `${loaderOptions.additionalData}\n${content}` : content
  103. };
  104. if (!sassOptions.logger) {
  105. const needEmitWarning = loaderOptions.warnRuleAsWarning !== false;
  106. const logger = loaderContext.getLogger("sass-loader");
  107. const formatSpan = span => `Warning on line ${span.start.line}, column ${span.start.column} of ${span.url || "-"}:${span.start.line}:${span.start.column}:\n`;
  108. const formatDebugSpan = span => `[debug:${span.start.line}:${span.start.column}] `;
  109. sassOptions.logger = {
  110. debug(message, loggerOptions) {
  111. let builtMessage = "";
  112. if (loggerOptions.span) {
  113. builtMessage = formatDebugSpan(loggerOptions.span);
  114. }
  115. builtMessage += message;
  116. logger.debug(builtMessage);
  117. },
  118. warn(message, loggerOptions) {
  119. let builtMessage = "";
  120. if (loggerOptions.deprecation) {
  121. builtMessage += "Deprecation ";
  122. }
  123. if (loggerOptions.span) {
  124. builtMessage += formatSpan(loggerOptions.span);
  125. }
  126. builtMessage += message;
  127. if (loggerOptions.span && loggerOptions.span.context) {
  128. builtMessage += `\n\n${loggerOptions.span.start.line} | ${loggerOptions.span.context}`;
  129. }
  130. if (loggerOptions.stack && loggerOptions.stack !== "null") {
  131. builtMessage += `\n\n${loggerOptions.stack}`;
  132. }
  133. if (needEmitWarning) {
  134. const warning = new Error(builtMessage);
  135. warning.name = "SassWarning";
  136. warning.stack = null;
  137. loaderContext.emitWarning(warning);
  138. } else {
  139. logger.warn(builtMessage);
  140. }
  141. }
  142. };
  143. }
  144. const isModernAPI = apiType === "modern" || apiType === "modern-compiler";
  145. const {
  146. resourcePath
  147. } = loaderContext;
  148. if (isModernAPI) {
  149. sassOptions.url = _url.default.pathToFileURL(resourcePath);
  150. // opt.outputStyle
  151. if (!sassOptions.style && isProductionLikeMode(loaderContext)) {
  152. sassOptions.style = "compressed";
  153. }
  154. if (useSourceMap) {
  155. sassOptions.sourceMap = true;
  156. sassOptions.sourceMapIncludeSources = true;
  157. }
  158. // If we are compiling sass and indentedSyntax isn't set, automatically set it.
  159. if (typeof sassOptions.syntax === "undefined") {
  160. const ext = _path.default.extname(resourcePath);
  161. if (ext && ext.toLowerCase() === ".scss") {
  162. sassOptions.syntax = "scss";
  163. } else if (ext && ext.toLowerCase() === ".sass") {
  164. sassOptions.syntax = "indented";
  165. } else if (ext && ext.toLowerCase() === ".css") {
  166. sassOptions.syntax = "css";
  167. }
  168. }
  169. sassOptions.loadPaths = [].concat(
  170. // We use `loadPaths` in context for resolver, so it should be always absolute
  171. (sassOptions.loadPaths ? sassOptions.loadPaths.slice() : []).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" ? ";" : ":") : []);
  172. sassOptions.importers = sassOptions.importers ? Array.isArray(sassOptions.importers) ? sassOptions.importers.slice() : [sassOptions.importers] : [];
  173. } else {
  174. sassOptions.file = resourcePath;
  175. // opt.outputStyle
  176. if (!sassOptions.outputStyle && isProductionLikeMode(loaderContext)) {
  177. sassOptions.outputStyle = "compressed";
  178. }
  179. if (useSourceMap) {
  180. // Deliberately overriding the sourceMap option here.
  181. // node-sass won't produce source maps if the data option is used and options.sourceMap is not a string.
  182. // In case it is a string, options.sourceMap should be a path where the source map is written.
  183. // But since we're using the data option, the source map will not actually be written, but
  184. // all paths in sourceMap.sources will be relative to that path.
  185. // Pretty complicated... :(
  186. sassOptions.sourceMap = true;
  187. sassOptions.outFile = _path.default.join(loaderContext.rootContext, "style.css.map");
  188. sassOptions.sourceMapContents = true;
  189. sassOptions.omitSourceMapUrl = true;
  190. sassOptions.sourceMapEmbed = false;
  191. }
  192. const ext = _path.default.extname(resourcePath);
  193. // If we are compiling sass and indentedSyntax isn't set, automatically set it.
  194. if (ext && ext.toLowerCase() === ".sass" && typeof sassOptions.indentedSyntax === "undefined") {
  195. sassOptions.indentedSyntax = true;
  196. } else {
  197. sassOptions.indentedSyntax = Boolean(sassOptions.indentedSyntax);
  198. }
  199. // Allow passing custom importers to `sass`/`node-sass`. Accepts `Function` or an array of `Function`s.
  200. sassOptions.importer = sassOptions.importer ? proxyCustomImporters(Array.isArray(sassOptions.importer) ? sassOptions.importer.slice() : [sassOptions.importer], loaderContext) : [];
  201. // Regression on the `sass-embedded` side
  202. if (loaderOptions.webpackImporter === false && sassOptions.importer.length === 0) {
  203. // eslint-disable-next-line no-undefined
  204. sassOptions.importer = undefined;
  205. }
  206. sassOptions.includePaths = [].concat(process.cwd()).concat(
  207. // We use `includePaths` in context for resolver, so it should be always absolute
  208. (sassOptions.includePaths ? sassOptions.includePaths.slice() : []).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" ? ";" : ":") : []);
  209. if (typeof sassOptions.charset === "undefined") {
  210. sassOptions.charset = true;
  211. }
  212. }
  213. return sassOptions;
  214. }
  215. const MODULE_REQUEST_REGEX = /^[^?]*~/;
  216. // Examples:
  217. // - ~package
  218. // - ~package/
  219. // - ~@org
  220. // - ~@org/
  221. // - ~@org/package
  222. // - ~@org/package/
  223. const IS_MODULE_IMPORT = /^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/]+\/)$/;
  224. const IS_PKG_SCHEME = /^pkg:/i;
  225. /**
  226. * When `sass`/`node-sass` tries to resolve an import, it uses a special algorithm.
  227. * Since the `sass-loader` uses webpack to resolve the modules, we need to simulate that algorithm.
  228. * This function returns an array of import paths to try.
  229. * The last entry in the array is always the original url to enable straight-forward webpack.config aliases.
  230. *
  231. * 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).
  232. * This reduces performance and `dart-sass` always do it on own side.
  233. *
  234. * @param {string} url
  235. * @param {boolean} forWebpackResolver
  236. * @param {boolean} fromImport
  237. * @returns {Array<string>}
  238. */
  239. function getPossibleRequests(
  240. // eslint-disable-next-line no-shadow
  241. url, forWebpackResolver = false, fromImport = false) {
  242. let request = url;
  243. // In case there is module request, send this to webpack resolver
  244. if (forWebpackResolver) {
  245. if (MODULE_REQUEST_REGEX.test(url)) {
  246. request = request.replace(MODULE_REQUEST_REGEX, "");
  247. }
  248. if (IS_PKG_SCHEME.test(url)) {
  249. request = `${request.slice(4)}`;
  250. return [...new Set([request, url])];
  251. }
  252. if (IS_MODULE_IMPORT.test(url) || IS_PKG_SCHEME.test(url)) {
  253. request = request[request.length - 1] === "/" ? request : `${request}/`;
  254. return [...new Set([request, url])];
  255. }
  256. }
  257. // Keep in mind: ext can also be something like '.datepicker' when the true extension is omitted and the filename contains a dot.
  258. // @see https://github.com/webpack-contrib/sass-loader/issues/167
  259. const extension = _path.default.extname(request).toLowerCase();
  260. // 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.
  261. // 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:
  262. // - imports where the URL ends with .css.
  263. // - imports where the URL begins http:// or https://.
  264. // - imports where the URL is written as a url().
  265. // - imports that have media queries.
  266. //
  267. // The `node-sass` package sends `@import` ending on `.css` to importer, it is bug, so we skip resolve
  268. // Also sass outputs as is `@import "style.css"`, but `@use "style.css"` should include CSS content
  269. if (extension === ".css") {
  270. return fromImport ? [] : [url];
  271. }
  272. const dirname = _path.default.dirname(request);
  273. const normalizedDirname = dirname === "." ? "" : `${dirname}/`;
  274. const basename = _path.default.basename(request);
  275. const basenameWithoutExtension = _path.default.basename(request, extension);
  276. return [...new Set([].concat(fromImport ? [`${normalizedDirname}_${basenameWithoutExtension}.import${extension}`, `${normalizedDirname}${basenameWithoutExtension}.import${extension}`] : []).concat([`${normalizedDirname}_${basename}`, `${normalizedDirname}${basename}`]).concat(forWebpackResolver ? [url] : []))];
  277. }
  278. function promiseResolve(callbackResolve) {
  279. return (context, request) => new Promise((resolve, reject) => {
  280. callbackResolve(context, request, (error, result) => {
  281. if (error) {
  282. reject(error);
  283. } else {
  284. resolve(result);
  285. }
  286. });
  287. });
  288. }
  289. async function startResolving(resolutionMap) {
  290. if (resolutionMap.length === 0) {
  291. return Promise.reject();
  292. }
  293. const [{
  294. possibleRequests
  295. }] = resolutionMap;
  296. if (possibleRequests.length === 0) {
  297. return Promise.reject();
  298. }
  299. const [{
  300. resolve,
  301. context
  302. }] = resolutionMap;
  303. try {
  304. return await resolve(context, possibleRequests[0]);
  305. } catch (_ignoreError) {
  306. const [, ...tailResult] = possibleRequests;
  307. if (tailResult.length === 0) {
  308. const [, ...tailResolutionMap] = resolutionMap;
  309. return startResolving(tailResolutionMap);
  310. }
  311. // eslint-disable-next-line no-param-reassign
  312. resolutionMap[0].possibleRequests = tailResult;
  313. return startResolving(resolutionMap);
  314. }
  315. }
  316. const IS_SPECIAL_MODULE_IMPORT = /^~[^/]+$/;
  317. // `[drive_letter]:\` + `\\[server]\[sharename]\`
  318. const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
  319. /**
  320. * @public
  321. * Create the resolve function used in the custom Sass importer.
  322. *
  323. * Can be used by external tools to mimic how `sass-loader` works, for example
  324. * in a Jest transform. Such usages will want to wrap `resolve.create` from
  325. * [`enhanced-resolve`]{@link https://github.com/webpack/enhanced-resolve} to
  326. * pass as the `resolverFactory` argument.
  327. *
  328. * @param {Function} resolverFactory - A factory function for creating a Webpack
  329. * resolver.
  330. * @param {Object} implementation - The imported Sass implementation, both
  331. * `sass` (Dart Sass) and `node-sass` are supported.
  332. * @param {string[]} [includePaths] - The list of include paths passed to Sass.
  333. *
  334. * @throws If a compatible Sass implementation cannot be found.
  335. */
  336. function getWebpackResolver(resolverFactory, implementation, includePaths = []) {
  337. const isModernSass = implementation && typeof implementation.compileStringAsync !== "undefined";
  338. // We only have one difference with the built-in sass resolution logic and out resolution logic:
  339. // First, we look at the files starting with `_`, then without `_` (i.e. `_name.sass`, `_name.scss`, `_name.css`, `name.sass`, `name.scss`, `name.css`),
  340. // although `sass` look together by extensions (i.e. `_name.sass`/`name.sass`/`_name.scss`/`name.scss`/`_name.css`/`name.css`).
  341. // It shouldn't be a problem because `sass` throw errors:
  342. // - on having `_name.sass` and `name.sass` (extension can be `sass`, `scss` or `css`) in the same directory
  343. // - on having `_name.sass` and `_name.scss` in the same directory
  344. //
  345. // Also `sass` prefer `sass`/`scss` over `css`.
  346. const sassModuleResolve = promiseResolve(resolverFactory({
  347. alias: [],
  348. aliasFields: [],
  349. conditionNames: [],
  350. descriptionFiles: [],
  351. extensions: [".sass", ".scss", ".css"],
  352. exportsFields: [],
  353. mainFields: [],
  354. mainFiles: ["_index", "index"],
  355. modules: [],
  356. restrictions: [/\.((sa|sc|c)ss)$/i],
  357. preferRelative: true
  358. }));
  359. const sassImportResolve = promiseResolve(resolverFactory({
  360. alias: [],
  361. aliasFields: [],
  362. conditionNames: [],
  363. descriptionFiles: [],
  364. extensions: [".sass", ".scss", ".css"],
  365. exportsFields: [],
  366. mainFields: [],
  367. mainFiles: ["_index.import", "_index", "index.import", "index"],
  368. modules: [],
  369. restrictions: [/\.((sa|sc|c)ss)$/i],
  370. preferRelative: true
  371. }));
  372. const webpackModuleResolve = promiseResolve(resolverFactory({
  373. dependencyType: "sass",
  374. conditionNames: ["sass", "style", "..."],
  375. mainFields: ["sass", "style", "main", "..."],
  376. mainFiles: ["_index", "index", "..."],
  377. extensions: [".sass", ".scss", ".css"],
  378. restrictions: [/\.((sa|sc|c)ss)$/i],
  379. preferRelative: true
  380. }));
  381. const webpackImportResolve = promiseResolve(resolverFactory({
  382. dependencyType: "sass",
  383. conditionNames: ["sass", "style", "..."],
  384. mainFields: ["sass", "style", "main", "..."],
  385. mainFiles: ["_index.import", "_index", "index.import", "index", "..."],
  386. extensions: [".sass", ".scss", ".css"],
  387. restrictions: [/\.((sa|sc|c)ss)$/i],
  388. preferRelative: true
  389. }));
  390. return (context, request, fromImport) => {
  391. // See https://github.com/webpack/webpack/issues/12340
  392. // Because `node-sass` calls our importer before `1. Filesystem imports relative to the base file.`
  393. // custom importer may not return `{ file: '/path/to/name.ext' }` and therefore our `context` will be relative
  394. if (!isModernSass && !_path.default.isAbsolute(context)) {
  395. return Promise.reject();
  396. }
  397. const originalRequest = request;
  398. const isFileScheme = originalRequest.slice(0, 5).toLowerCase() === "file:";
  399. if (isFileScheme) {
  400. try {
  401. // eslint-disable-next-line no-param-reassign
  402. request = _url.default.fileURLToPath(originalRequest);
  403. } catch (ignoreError) {
  404. // eslint-disable-next-line no-param-reassign
  405. request = request.slice(7);
  406. }
  407. }
  408. let resolutionMap = [];
  409. const needEmulateSassResolver =
  410. // `sass` doesn't support module import
  411. !IS_SPECIAL_MODULE_IMPORT.test(request) &&
  412. // don't handle `pkg:` scheme
  413. !IS_PKG_SCHEME.test(request) &&
  414. // We need improve absolute paths handling.
  415. // Absolute paths should be resolved:
  416. // - Server-relative URLs - `<context>/path/to/file.ext` (where `<context>` is root context)
  417. // - Absolute path - `/full/path/to/file.ext` or `C:\\full\path\to\file.ext`
  418. !isFileScheme && !originalRequest.startsWith("/") && !IS_NATIVE_WIN32_PATH.test(originalRequest);
  419. if (includePaths.length > 0 && needEmulateSassResolver) {
  420. // The order of import precedence is as follows:
  421. //
  422. // 1. Filesystem imports relative to the base file.
  423. // 2. Custom importer imports.
  424. // 3. Filesystem imports relative to the working directory.
  425. // 4. Filesystem imports relative to an `includePaths` path.
  426. // 5. Filesystem imports relative to a `SASS_PATH` path.
  427. //
  428. // `sass` run custom importers before `3`, `4` and `5` points, we need to emulate this behavior to avoid wrong resolution.
  429. const sassPossibleRequests = getPossibleRequests(request, false, fromImport);
  430. // `node-sass` calls our importer before `1. Filesystem imports relative to the base file.`, so we need emulate this too
  431. if (!isModernSass) {
  432. resolutionMap = resolutionMap.concat({
  433. resolve: fromImport ? sassImportResolve : sassModuleResolve,
  434. context: _path.default.dirname(context),
  435. possibleRequests: sassPossibleRequests
  436. });
  437. }
  438. resolutionMap = resolutionMap.concat(
  439. // eslint-disable-next-line no-shadow
  440. includePaths.map(context => {
  441. return {
  442. resolve: fromImport ? sassImportResolve : sassModuleResolve,
  443. context,
  444. possibleRequests: sassPossibleRequests
  445. };
  446. }));
  447. }
  448. const webpackPossibleRequests = getPossibleRequests(request, true, fromImport);
  449. resolutionMap = resolutionMap.concat({
  450. resolve: fromImport ? webpackImportResolve : webpackModuleResolve,
  451. context: _path.default.dirname(context),
  452. possibleRequests: webpackPossibleRequests
  453. });
  454. return startResolving(resolutionMap);
  455. };
  456. }
  457. const MATCH_CSS = /\.css$/i;
  458. function getModernWebpackImporter(loaderContext, implementation, loadPaths) {
  459. const resolve = getWebpackResolver(loaderContext.getResolve, implementation, loadPaths);
  460. return {
  461. async canonicalize(originalUrl, context) {
  462. const {
  463. fromImport
  464. } = context;
  465. const prev = context.containingUrl ? _url.default.fileURLToPath(context.containingUrl.toString()) : loaderContext.resourcePath;
  466. let result;
  467. try {
  468. result = await resolve(prev, originalUrl, fromImport);
  469. } catch (err) {
  470. // If no stylesheets are found, the importer should return null.
  471. return null;
  472. }
  473. loaderContext.addDependency(_path.default.normalize(result));
  474. return _url.default.pathToFileURL(result);
  475. },
  476. async load(canonicalUrl) {
  477. const ext = _path.default.extname(canonicalUrl.pathname);
  478. let syntax;
  479. if (ext && ext.toLowerCase() === ".scss") {
  480. syntax = "scss";
  481. } else if (ext && ext.toLowerCase() === ".sass") {
  482. syntax = "indented";
  483. } else if (ext && ext.toLowerCase() === ".css") {
  484. syntax = "css";
  485. } else {
  486. // Fallback to default value
  487. syntax = "scss";
  488. }
  489. try {
  490. // eslint-disable-next-line no-shadow
  491. const contents = await new Promise((resolve, reject) => {
  492. // Old version of `enhanced-resolve` supports only path as a string
  493. // TODO simplify in the next major release and pass URL
  494. const canonicalPath = _url.default.fileURLToPath(canonicalUrl);
  495. loaderContext.fs.readFile(canonicalPath, "utf8", (err, content) => {
  496. if (err) {
  497. reject(err);
  498. return;
  499. }
  500. resolve(content);
  501. });
  502. });
  503. return {
  504. contents,
  505. syntax,
  506. sourceMapUrl: canonicalUrl
  507. };
  508. } catch (err) {
  509. return null;
  510. }
  511. }
  512. };
  513. }
  514. function getWebpackImporter(loaderContext, implementation, includePaths) {
  515. const resolve = getWebpackResolver(loaderContext.getResolve, implementation, includePaths);
  516. return function importer(originalUrl, prev, done) {
  517. const {
  518. fromImport
  519. } = this;
  520. resolve(prev, originalUrl,
  521. // For `node-sass`
  522. typeof fromImport === "undefined" ? true : fromImport).then(result => {
  523. // Add the result as dependency.
  524. // Although we're also using stats.includedFiles, this might come in handy when an error occurs.
  525. // In this case, we don't get stats.includedFiles from node-sass/sass.
  526. loaderContext.addDependency(_path.default.normalize(result));
  527. // By removing the CSS file extension, we trigger node-sass to include the CSS file instead of just linking it.
  528. done({
  529. file: result.replace(MATCH_CSS, "")
  530. });
  531. })
  532. // Catch all resolving errors, return the original file and pass responsibility back to other custom importers
  533. .catch(() => {
  534. done({
  535. file: originalUrl
  536. });
  537. });
  538. };
  539. }
  540. let nodeSassJobQueue = null;
  541. const sassModernCompilers = new WeakMap();
  542. /**
  543. * Verifies that the implementation and version of Sass is supported by this loader.
  544. *
  545. * @param {Object} loaderContext
  546. * @param {Object} implementation
  547. * @param {"legacy" | "modern" | "modern-compiler"} apiType
  548. * @returns {Function}
  549. */
  550. function getCompileFn(loaderContext, implementation, apiType) {
  551. if (typeof implementation.compileStringAsync !== "undefined") {
  552. if (apiType === "modern") {
  553. return sassOptions => {
  554. const {
  555. data,
  556. ...rest
  557. } = sassOptions;
  558. return implementation.compileStringAsync(data, rest);
  559. };
  560. }
  561. if (apiType === "modern-compiler") {
  562. return async sassOptions => {
  563. // eslint-disable-next-line no-underscore-dangle
  564. const webpackCompiler = loaderContext._compiler;
  565. const {
  566. data,
  567. ...rest
  568. } = sassOptions;
  569. // Some people can run the loader in a multi-threading way;
  570. // there is no webpack compiler object in such case.
  571. if (webpackCompiler) {
  572. if (!sassModernCompilers.has(webpackCompiler)) {
  573. // Create a long-running compiler process that can be reused
  574. // for compiling individual files.
  575. const compiler = await implementation.initAsyncCompiler();
  576. // Check again because awaiting the initialization function
  577. // introduces a race condition.
  578. if (!sassModernCompilers.has(webpackCompiler)) {
  579. sassModernCompilers.set(webpackCompiler, compiler);
  580. webpackCompiler.hooks.shutdown.tap("sass-loader", () => {
  581. compiler.dispose();
  582. });
  583. } else {
  584. compiler.dispose();
  585. }
  586. }
  587. return sassModernCompilers.get(webpackCompiler).compileStringAsync(data, rest);
  588. }
  589. return implementation.compileStringAsync(data, rest);
  590. };
  591. }
  592. return sassOptions => new Promise((resolve, reject) => {
  593. implementation.render(sassOptions, (error, result) => {
  594. if (error) {
  595. reject(error);
  596. return;
  597. }
  598. resolve(result);
  599. });
  600. });
  601. }
  602. if (apiType === "modern" || apiType === "modern-compiler") {
  603. throw new Error("Modern API is not supported for 'node-sass'");
  604. }
  605. // There is an issue with node-sass when async custom importers are used
  606. // See https://github.com/sass/node-sass/issues/857#issuecomment-93594360
  607. // We need to use a job queue to make sure that one thread is always available to the UV lib
  608. if (nodeSassJobQueue === null) {
  609. const threadPoolSize = Number(process.env.UV_THREADPOOL_SIZE || 4);
  610. // Only used for `node-sass`, so let's load it lazily
  611. // eslint-disable-next-line global-require
  612. const async = require("neo-async");
  613. nodeSassJobQueue = async.queue(implementation.render.bind(implementation), threadPoolSize - 1);
  614. }
  615. return sassOptions => new Promise((resolve, reject) => {
  616. nodeSassJobQueue.push.bind(nodeSassJobQueue)(sassOptions, (error, result) => {
  617. if (error) {
  618. reject(error);
  619. return;
  620. }
  621. resolve(result);
  622. });
  623. });
  624. }
  625. const ABSOLUTE_SCHEME = /^[A-Za-z0-9+\-.]+:/;
  626. /**
  627. * @param {string} source
  628. * @returns {"absolute" | "scheme-relative" | "path-absolute" | "path-absolute"}
  629. */
  630. function getURLType(source) {
  631. if (source[0] === "/") {
  632. if (source[1] === "/") {
  633. return "scheme-relative";
  634. }
  635. return "path-absolute";
  636. }
  637. if (IS_NATIVE_WIN32_PATH.test(source)) {
  638. return "path-absolute";
  639. }
  640. return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
  641. }
  642. function normalizeSourceMap(map, rootContext) {
  643. const newMap = map;
  644. // result.map.file is an optional property that provides the output filename.
  645. // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
  646. // eslint-disable-next-line no-param-reassign
  647. if (typeof newMap.file !== "undefined") {
  648. delete newMap.file;
  649. }
  650. // eslint-disable-next-line no-param-reassign
  651. newMap.sourceRoot = "";
  652. // node-sass returns POSIX paths, that's why we need to transform them back to native paths.
  653. // This fixes an error on windows where the source-map module cannot resolve the source maps.
  654. // @see https://github.com/webpack-contrib/sass-loader/issues/366#issuecomment-279460722
  655. // eslint-disable-next-line no-param-reassign
  656. newMap.sources = newMap.sources.map(source => {
  657. const sourceType = getURLType(source);
  658. // Do no touch `scheme-relative`, `path-absolute` and `absolute` types (except `file:`)
  659. if (sourceType === "absolute" && /^file:/i.test(source)) {
  660. return _url.default.fileURLToPath(source);
  661. } else if (sourceType === "path-relative") {
  662. return _path.default.resolve(rootContext, _path.default.normalize(source));
  663. }
  664. return source;
  665. });
  666. return newMap;
  667. }
  668. function errorFactory(error) {
  669. let message;
  670. if (error.formatted) {
  671. message = error.formatted.replace(/^(.+)?Error: /, "");
  672. } else {
  673. // Keep original error if `sassError.formatted` is unavailable
  674. message = (error.message || error.toString()).replace(/^(.+)?Error: /, "");
  675. }
  676. const obj = new Error(message, {
  677. cause: error
  678. });
  679. obj.name = error.name;
  680. obj.stack = null;
  681. return obj;
  682. }