index.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. 'use strict';
  2. const path = require('path');
  3. const { Transform } = require('stream');
  4. const picocolors = require('picocolors');
  5. const PluginError = require('plugin-error');
  6. const replaceExtension = require('replace-ext');
  7. const stripAnsi = require('strip-ansi');
  8. const clonedeep = require('lodash.clonedeep');
  9. const applySourceMap = require('vinyl-sourcemaps-apply');
  10. const PLUGIN_NAME = 'gulp-sass';
  11. const MISSING_COMPILER_MESSAGE = `
  12. gulp-sass no longer has a default Sass compiler; please set one yourself.
  13. Both the "sass" and "node-sass" packages are permitted.
  14. For example, in your gulpfile:
  15. const sass = require('gulp-sass')(require('sass'));
  16. `;
  17. const transfob = (transform) => new Transform({ transform, objectMode: true });
  18. /**
  19. * Handles returning the file to the stream
  20. */
  21. const filePush = (file, sassObject, callback) => {
  22. // Build Source Maps!
  23. if (sassObject.map) {
  24. // Transform map into JSON
  25. const sassMap = JSON.parse(sassObject.map.toString());
  26. // Grab the stdout and transform it into stdin
  27. const sassMapFile = sassMap.file.replace(/^stdout$/, 'stdin');
  28. // Grab the base filename that's being worked on
  29. const sassFileSrc = file.relative;
  30. // Grab the path portion of the file that's being worked on
  31. const sassFileSrcPath = path.dirname(sassFileSrc);
  32. if (sassFileSrcPath) {
  33. const sourceFileIndex = sassMap.sources.indexOf(sassMapFile);
  34. // Prepend the path to all files in the sources array except the file that's being worked on
  35. sassMap.sources = sassMap.sources.map((source, index) => (
  36. index === sourceFileIndex
  37. ? source
  38. : path.join(sassFileSrcPath, source)
  39. ));
  40. }
  41. // Remove 'stdin' from souces and replace with filenames!
  42. sassMap.sources = sassMap.sources.filter((src) => src !== 'stdin' && src);
  43. // Replace the map file with the original filename (but new extension)
  44. sassMap.file = replaceExtension(sassFileSrc, '.css');
  45. // Apply the map
  46. applySourceMap(file, sassMap);
  47. }
  48. file.contents = sassObject.css;
  49. file.path = replaceExtension(file.path, '.css');
  50. if (file.stat) {
  51. file.stat.atime = file.stat.mtime = file.stat.ctime = new Date();
  52. }
  53. callback(null, file);
  54. };
  55. /**
  56. * Handles error message
  57. */
  58. const handleError = (error, file, callback) => {
  59. const filePath = (error.file === 'stdin' ? file.path : error.file) || file.path;
  60. const relativePath = path.relative(process.cwd(), filePath);
  61. const message = `${picocolors.underline(relativePath)}\n${error.formatted}`;
  62. error.messageFormatted = message;
  63. error.messageOriginal = error.message;
  64. error.message = stripAnsi(message);
  65. error.relativePath = relativePath;
  66. return callback(new PluginError(PLUGIN_NAME, error));
  67. };
  68. /**
  69. * Main Gulp Sass function
  70. */
  71. // eslint-disable-next-line arrow-body-style
  72. const gulpSass = (options, sync) => {
  73. return transfob((file, encoding, callback) => {
  74. if (file.isNull()) {
  75. callback(null, file);
  76. return;
  77. }
  78. if (file.isStream()) {
  79. callback(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
  80. return;
  81. }
  82. if (path.basename(file.path).startsWith('_')) {
  83. callback();
  84. return;
  85. }
  86. if (!file.contents.length) {
  87. file.path = replaceExtension(file.path, '.css');
  88. callback(null, file);
  89. return;
  90. }
  91. const opts = clonedeep(options || {});
  92. opts.data = file.contents.toString();
  93. // We set the file path here so that libsass can correctly resolve import paths
  94. opts.file = file.path;
  95. // Ensure `indentedSyntax` is true if a `.sass` file
  96. if (path.extname(file.path) === '.sass') {
  97. opts.indentedSyntax = true;
  98. }
  99. // Ensure file's parent directory in the include path
  100. if (opts.includePaths) {
  101. if (typeof opts.includePaths === 'string') {
  102. opts.includePaths = [opts.includePaths];
  103. }
  104. } else {
  105. opts.includePaths = [];
  106. }
  107. opts.includePaths.unshift(path.dirname(file.path));
  108. // Generate Source Maps if the source-map plugin is present
  109. if (file.sourceMap) {
  110. opts.sourceMap = file.path;
  111. opts.omitSourceMapUrl = true;
  112. opts.sourceMapContents = true;
  113. }
  114. if (sync !== true) {
  115. /**
  116. * Async Sass render
  117. */
  118. gulpSass.compiler.render(opts, (error, obj) => {
  119. if (error) {
  120. handleError(error, file, callback);
  121. return;
  122. }
  123. filePush(file, obj, callback);
  124. });
  125. } else {
  126. /**
  127. * Sync Sass render
  128. */
  129. try {
  130. filePush(file, gulpSass.compiler.renderSync(opts), callback);
  131. } catch (error) {
  132. handleError(error, file, callback);
  133. }
  134. }
  135. });
  136. };
  137. /**
  138. * Sync Sass render
  139. */
  140. gulpSass.sync = (options) => gulpSass(options, true);
  141. /**
  142. * Log errors nicely
  143. */
  144. gulpSass.logError = function logError(error) {
  145. const message = new PluginError('sass', error.messageFormatted).toString();
  146. process.stderr.write(`${message}\n`);
  147. this.emit('end');
  148. };
  149. module.exports = (compiler) => {
  150. if (!compiler || !compiler.render) {
  151. const message = new PluginError(
  152. PLUGIN_NAME,
  153. MISSING_COMPILER_MESSAGE,
  154. { showProperties: false },
  155. ).toString();
  156. process.stderr.write(`${message}\n`);
  157. process.exit(1);
  158. }
  159. gulpSass.compiler = compiler;
  160. return gulpSass;
  161. };