webpackImporter.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. /**
  3. * @name PromisedResolve
  4. * @type {Function}
  5. * @param {string} dir
  6. * @param {string} request
  7. * @returns Promise
  8. */
  9. /**
  10. * @name Importer
  11. * @type {Function}
  12. * @param {string} url
  13. * @param {string} prev
  14. * @param {Function<Error, string>} done
  15. */
  16. const path = require('path');
  17. const importsToResolve = require('./importsToResolve');
  18. const matchCss = /\.css$/;
  19. /**
  20. * Returns an importer that uses webpack's resolving algorithm.
  21. *
  22. * It's important that the returned function has the correct number of arguments
  23. * (based on whether the call is sync or async) because otherwise node-sass doesn't exit.
  24. *
  25. * @param {string} resourcePath
  26. * @param {PromisedResolve} resolve
  27. * @param {Function<string>} addNormalizedDependency
  28. * @returns {Importer}
  29. */
  30. function webpackImporter(resourcePath, resolve, addNormalizedDependency) {
  31. function dirContextFrom(fileContext) {
  32. return path.dirname(
  33. // The first file is 'stdin' when we're using the data option
  34. fileContext === 'stdin' ? resourcePath : fileContext
  35. );
  36. }
  37. // eslint-disable-next-line no-shadow
  38. function startResolving(dir, importsToResolve) {
  39. return importsToResolve.length === 0
  40. ? Promise.reject()
  41. : resolve(dir, importsToResolve[0]).then(
  42. (resolvedFile) => {
  43. // Add the resolvedFilename as dependency. Although we're also using stats.includedFiles, this might come
  44. // in handy when an error occurs. In this case, we don't get stats.includedFiles from node-sass.
  45. addNormalizedDependency(resolvedFile);
  46. return {
  47. // By removing the CSS file extension, we trigger node-sass to include the CSS file instead of just linking it.
  48. file: resolvedFile.replace(matchCss, ''),
  49. };
  50. },
  51. () => {
  52. const [, ...tailResult] = importsToResolve;
  53. return startResolving(dir, tailResult);
  54. }
  55. );
  56. }
  57. return (url, prev, done) => {
  58. startResolving(dirContextFrom(prev), importsToResolve(url))
  59. // Catch all resolving errors, return the original file and pass responsibility back to other custom importers
  60. .catch(() => {
  61. return {
  62. file: url,
  63. };
  64. })
  65. .then(done);
  66. };
  67. }
  68. module.exports = webpackImporter;