utils.js 17 KB

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