loader.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. 'use strict';
  2. const path = require('path');
  3. const async = require('neo-async');
  4. const pify = require('pify');
  5. const semver = require('semver');
  6. const formatSassError = require('./formatSassError');
  7. const webpackImporter = require('./webpackImporter');
  8. const normalizeOptions = require('./normalizeOptions');
  9. let nodeSassJobQueue = null;
  10. // Very hacky check
  11. function hasGetResolve(loaderContext) {
  12. return (
  13. loaderContext.getResolve &&
  14. // eslint-disable-next-line no-underscore-dangle
  15. loaderContext._compiler &&
  16. // eslint-disable-next-line no-underscore-dangle
  17. loaderContext._compiler.resolverFactory &&
  18. // eslint-disable-next-line no-underscore-dangle
  19. loaderContext._compiler.resolverFactory._create &&
  20. /cachedCleverMerge/.test(
  21. // eslint-disable-next-line no-underscore-dangle
  22. loaderContext._compiler.resolverFactory._create.toString()
  23. )
  24. );
  25. }
  26. /**
  27. * The sass-loader makes node-sass and dart-sass available to webpack modules.
  28. *
  29. * @this {LoaderContext}
  30. * @param {string} content
  31. */
  32. function sassLoader(content) {
  33. const callback = this.async();
  34. const isSync = typeof callback !== 'function';
  35. const self = this;
  36. const { resourcePath } = this;
  37. function addNormalizedDependency(file) {
  38. // node-sass returns POSIX paths
  39. self.dependency(path.normalize(file));
  40. }
  41. if (isSync) {
  42. throw new Error(
  43. 'Synchronous compilation is not supported anymore. See https://github.com/webpack-contrib/sass-loader/issues/333'
  44. );
  45. }
  46. let resolve = pify(this.resolve);
  47. // Supported since v4.36.0
  48. if (hasGetResolve(self)) {
  49. resolve = this.getResolve({
  50. mainFields: ['sass', 'style', '...'],
  51. extensions: ['.scss', '.sass', '.css', '...'],
  52. });
  53. }
  54. const options = normalizeOptions(
  55. this,
  56. content,
  57. webpackImporter(resourcePath, resolve, addNormalizedDependency)
  58. );
  59. // Skip empty files, otherwise it will stop webpack, see issue #21
  60. if (options.data.trim() === '') {
  61. callback(null, '');
  62. return;
  63. }
  64. const render = getRenderFuncFromSassImpl(
  65. // eslint-disable-next-line import/no-extraneous-dependencies, global-require
  66. options.implementation || getDefaultSassImpl()
  67. );
  68. render(options, (err, result) => {
  69. if (err) {
  70. formatSassError(err, this.resourcePath);
  71. if (err.file) {
  72. this.dependency(err.file);
  73. }
  74. callback(err);
  75. return;
  76. }
  77. if (result.map && result.map !== '{}') {
  78. // eslint-disable-next-line no-param-reassign
  79. result.map = JSON.parse(result.map);
  80. // result.map.file is an optional property that provides the output filename.
  81. // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
  82. // eslint-disable-next-line no-param-reassign
  83. delete result.map.file;
  84. // One of the sources is 'stdin' according to dart-sass/node-sass because we've used the data input.
  85. // Now let's override that value with the correct relative path.
  86. // Since we specified options.sourceMap = path.join(process.cwd(), "/sass.map"); in normalizeOptions,
  87. // we know that this path is relative to process.cwd(). This is how node-sass works.
  88. // eslint-disable-next-line no-param-reassign
  89. const stdinIndex = result.map.sources.findIndex(
  90. (source) => source.indexOf('stdin') !== -1
  91. );
  92. if (stdinIndex !== -1) {
  93. // eslint-disable-next-line no-param-reassign
  94. result.map.sources[stdinIndex] = path.relative(
  95. process.cwd(),
  96. resourcePath
  97. );
  98. }
  99. // node-sass returns POSIX paths, that's why we need to transform them back to native paths.
  100. // This fixes an error on windows where the source-map module cannot resolve the source maps.
  101. // @see https://github.com/webpack-contrib/sass-loader/issues/366#issuecomment-279460722
  102. // eslint-disable-next-line no-param-reassign
  103. result.map.sourceRoot = path.normalize(result.map.sourceRoot);
  104. // eslint-disable-next-line no-param-reassign
  105. result.map.sources = result.map.sources.map(path.normalize);
  106. } else {
  107. // eslint-disable-next-line no-param-reassign
  108. result.map = null;
  109. }
  110. result.stats.includedFiles.forEach(addNormalizedDependency);
  111. callback(null, result.css.toString(), result.map);
  112. });
  113. }
  114. /**
  115. * Verifies that the implementation and version of Sass is supported by this loader.
  116. *
  117. * @param {Object} module
  118. * @returns {Function}
  119. */
  120. function getRenderFuncFromSassImpl(module) {
  121. const { info } = module;
  122. const components = info.split('\t');
  123. if (components.length < 2) {
  124. throw new Error(`Unknown Sass implementation "${info}".`);
  125. }
  126. const [implementation, version] = components;
  127. if (!semver.valid(version)) {
  128. throw new Error(`Invalid Sass version "${version}".`);
  129. }
  130. if (implementation === 'dart-sass') {
  131. if (!semver.satisfies(version, '^1.3.0')) {
  132. throw new Error(
  133. `Dart Sass version ${version} is incompatible with ^1.3.0.`
  134. );
  135. }
  136. return module.render.bind(module);
  137. } else if (implementation === 'node-sass') {
  138. if (!semver.satisfies(version, '^4.0.0')) {
  139. throw new Error(
  140. `Node Sass version ${version} is incompatible with ^4.0.0.`
  141. );
  142. }
  143. // There is an issue with node-sass when async custom importers are used
  144. // See https://github.com/sass/node-sass/issues/857#issuecomment-93594360
  145. // We need to use a job queue to make sure that one thread is always available to the UV lib
  146. if (nodeSassJobQueue === null) {
  147. const threadPoolSize = Number(process.env.UV_THREADPOOL_SIZE || 4);
  148. nodeSassJobQueue = async.queue(
  149. module.render.bind(module),
  150. threadPoolSize - 1
  151. );
  152. }
  153. return nodeSassJobQueue.push.bind(nodeSassJobQueue);
  154. }
  155. throw new Error(`Unknown Sass implementation "${implementation}".`);
  156. }
  157. function getDefaultSassImpl() {
  158. let sassImplPkg = 'node-sass';
  159. try {
  160. require.resolve('node-sass');
  161. } catch (error) {
  162. try {
  163. require.resolve('sass');
  164. sassImplPkg = 'sass';
  165. } catch (ignoreError) {
  166. sassImplPkg = 'node-sass';
  167. }
  168. }
  169. // eslint-disable-next-line import/no-dynamic-require, global-require
  170. return require(sassImplPkg);
  171. }
  172. module.exports = sassLoader;