You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

201 lines
6.8 KiB

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