utils.js 17 KB

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