index.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. "use strict";
  2. //var fs = require("fs");
  3. var assign = require("object-assign");
  4. var loaderUtils = require("loader-utils");
  5. var objectHash = require("object-hash");
  6. var createCache = require("loader-fs-cache");
  7. var pkg = require("./package.json");
  8. var cache = createCache("eslint-loader");
  9. var engines = {};
  10. /**
  11. * Class representing an ESLintError.
  12. * @extends Error
  13. */
  14. class ESLintError extends Error {
  15. /**
  16. * Create an ESLintError.
  17. * @param {string} messages - Formatted eslint errors.
  18. */
  19. constructor(messages) {
  20. super();
  21. this.name = "ESLintError";
  22. this.message = messages;
  23. this.stack = "";
  24. }
  25. /**
  26. * Returns a stringified representation of our error. This method is called
  27. * when an error is consumed by console methods
  28. * ex: console.error(new ESLintError(formattedMessage))
  29. * @return {string} error - A stringified representation of the error.
  30. */
  31. inspect() {
  32. return this.message;
  33. }
  34. }
  35. /**
  36. * printLinterOutput
  37. *
  38. * @param {Object} eslint.executeOnText return value
  39. * @param {Object} config eslint configuration
  40. * @param {Object} webpack webpack instance
  41. * @return {void}
  42. */
  43. function printLinterOutput(res, config, webpack) {
  44. // skip ignored file warning
  45. if (
  46. !(
  47. res.warningCount === 1 &&
  48. res.results[0].messages[0] &&
  49. res.results[0].messages[0].message &&
  50. res.results[0].messages[0].message.indexOf("ignore") > 1
  51. )
  52. ) {
  53. // quiet filter done now
  54. // eslint allow rules to be specified in the input between comments
  55. // so we can found warnings defined in the input itself
  56. if (res.warningCount && config.quiet) {
  57. res.warningCount = 0;
  58. res.results[0].warningCount = 0;
  59. res.results[0].messages = res.results[0].messages.filter(function(
  60. message
  61. ) {
  62. return message.severity !== 1;
  63. });
  64. }
  65. // if enabled, use eslint auto-fixing where possible
  66. if (
  67. config.fix &&
  68. (res.results[0].output !== res.src ||
  69. res.results[0].fixableErrorCount > 0 ||
  70. res.results[0].fixableWarningCount > 0)
  71. ) {
  72. var eslint = require(config.eslintPath);
  73. eslint.CLIEngine.outputFixes(res);
  74. }
  75. if (res.errorCount || res.warningCount) {
  76. // add filename for each results so formatter can have relevant filename
  77. res.results.forEach(function(r) {
  78. r.filePath = webpack.resourcePath;
  79. });
  80. var messages = config.formatter(res.results);
  81. if (config.outputReport && config.outputReport.filePath) {
  82. var reportOutput;
  83. // if a different formatter is passed in as an option use that
  84. if (config.outputReport.formatter) {
  85. reportOutput = config.outputReport.formatter(res.results);
  86. } else {
  87. reportOutput = messages;
  88. }
  89. var filePath = loaderUtils.interpolateName(
  90. webpack,
  91. config.outputReport.filePath,
  92. {
  93. content: res.results
  94. .map(function(r) {
  95. return r.source;
  96. })
  97. .join("\n")
  98. }
  99. );
  100. webpack.emitFile(filePath, reportOutput);
  101. }
  102. // default behavior: emit error only if we have errors
  103. var emitter = res.errorCount ? webpack.emitError : webpack.emitWarning;
  104. // force emitError or emitWarning if user want this
  105. if (config.emitError) {
  106. emitter = webpack.emitError;
  107. } else if (config.emitWarning) {
  108. emitter = webpack.emitWarning;
  109. }
  110. if (emitter) {
  111. if (config.failOnError && res.errorCount) {
  112. throw new ESLintError(
  113. "Module failed because of a eslint error.\n" + messages
  114. );
  115. } else if (config.failOnWarning && res.warningCount) {
  116. throw new ESLintError(
  117. "Module failed because of a eslint warning.\n" + messages
  118. );
  119. }
  120. emitter(new ESLintError(messages));
  121. } else {
  122. throw new Error(
  123. "Your module system doesn't support emitWarning. " +
  124. "Update available? \n" +
  125. messages
  126. );
  127. }
  128. }
  129. }
  130. }
  131. /**
  132. * webpack loader
  133. *
  134. * @param {String|Buffer} input JavaScript string
  135. * @param {Object} map input source map
  136. * @return {void}
  137. */
  138. module.exports = function(input, map) {
  139. var webpack = this;
  140. var userOptions = assign(
  141. // user defaults
  142. (webpack.options && webpack.options.eslint) || webpack.query || {},
  143. // loader query string
  144. loaderUtils.getOptions(webpack)
  145. );
  146. var userEslintPath = userOptions.eslintPath;
  147. var config = assign(
  148. // loader defaults
  149. {
  150. cacheIdentifier: JSON.stringify({
  151. "eslint-loader": pkg.version,
  152. eslint: require(userEslintPath || "eslint").version
  153. }),
  154. eslintPath: "eslint"
  155. },
  156. userOptions
  157. );
  158. if (typeof config.formatter === "string") {
  159. try {
  160. config.formatter = require(config.formatter);
  161. if (
  162. config.formatter &&
  163. typeof config.formatter !== "function" &&
  164. typeof config.formatter.default === "function"
  165. ) {
  166. config.formatter = config.formatter.default;
  167. }
  168. } catch (_) {
  169. // ignored
  170. }
  171. }
  172. if (config.formatter == null || typeof config.formatter !== "function") {
  173. if (userEslintPath) {
  174. try {
  175. config.formatter = require(userEslintPath + "/lib/formatters/stylish");
  176. } catch (e) {
  177. config.formatter = require("eslint/lib/formatters/stylish");
  178. }
  179. } else {
  180. config.formatter = require("eslint/lib/formatters/stylish");
  181. }
  182. }
  183. var cacheDirectory = config.cache;
  184. var cacheIdentifier = config.cacheIdentifier;
  185. delete config.cacheIdentifier;
  186. // Create the engine only once per config
  187. var configHash = objectHash(config);
  188. if (!engines[configHash]) {
  189. var eslint = require(config.eslintPath);
  190. engines[configHash] = new eslint.CLIEngine(config);
  191. }
  192. webpack.cacheable();
  193. var resourcePath = webpack.resourcePath;
  194. var cwd = process.cwd();
  195. // remove cwd from resource path in case webpack has been started from project
  196. // root, to allow having relative paths in .eslintignore
  197. if (resourcePath.indexOf(cwd) === 0) {
  198. resourcePath = resourcePath.substr(cwd.length + 1);
  199. }
  200. var engine = engines[configHash];
  201. // return early if cached
  202. if (config.cache) {
  203. var callback = webpack.async();
  204. return cache(
  205. {
  206. directory: cacheDirectory,
  207. identifier: cacheIdentifier,
  208. options: config,
  209. source: input,
  210. transform: function() {
  211. return lint(engine, input, resourcePath);
  212. }
  213. },
  214. function(err, res) {
  215. if (err) {
  216. return callback(err);
  217. }
  218. try {
  219. printLinterOutput(
  220. assign({}, res || {}, { src: input }),
  221. config,
  222. webpack
  223. );
  224. } catch (e) {
  225. err = e;
  226. }
  227. return callback(err, input, map);
  228. }
  229. );
  230. }
  231. printLinterOutput(lint(engine, input, resourcePath), config, webpack);
  232. webpack.callback(null, input, map);
  233. };
  234. function lint(engine, input, resourcePath) {
  235. return engine.executeOnText(input, resourcePath, true);
  236. }