index.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 eslintPkgPath = "eslint/package.json";
  147. var userEslintPath = eslintPkgPath;
  148. if (userOptions.eslintPath) {
  149. userEslintPath = userOptions.eslintPath + "/package.json";
  150. }
  151. var eslintVersion;
  152. try {
  153. eslintVersion = require(require.resolve(userEslintPath)).version;
  154. } catch (_) {
  155. // ignored
  156. }
  157. if (!eslintVersion) {
  158. try {
  159. eslintVersion = require(require.resolve(eslintPkgPath)).version;
  160. } catch (_) {
  161. // ignored
  162. }
  163. }
  164. var config = assign(
  165. // loader defaults
  166. {
  167. cacheIdentifier: JSON.stringify({
  168. "eslint-loader": pkg.version,
  169. eslint: eslintVersion || "unknown version"
  170. }),
  171. eslintPath: "eslint"
  172. },
  173. userOptions
  174. );
  175. if (typeof config.formatter === "string") {
  176. try {
  177. config.formatter = require(config.formatter);
  178. if (
  179. config.formatter &&
  180. typeof config.formatter !== "function" &&
  181. typeof config.formatter.default === "function"
  182. ) {
  183. config.formatter = config.formatter.default;
  184. }
  185. } catch (_) {
  186. // ignored
  187. }
  188. }
  189. var cacheDirectory = config.cache;
  190. var cacheIdentifier = config.cacheIdentifier;
  191. delete config.cacheIdentifier;
  192. // Create the engine only once per config
  193. var configHash = objectHash(config);
  194. if (!engines[configHash]) {
  195. var eslint = require(config.eslintPath);
  196. engines[configHash] = new eslint.CLIEngine(config);
  197. }
  198. var engine = engines[configHash];
  199. if (config.formatter == null || typeof config.formatter !== "function") {
  200. config.formatter = engine.getFormatter("stylish");
  201. }
  202. webpack.cacheable();
  203. var resourcePath = webpack.resourcePath;
  204. var cwd = process.cwd();
  205. // remove cwd from resource path in case webpack has been started from project
  206. // root, to allow having relative paths in .eslintignore
  207. if (resourcePath.indexOf(cwd) === 0) {
  208. resourcePath = resourcePath.substr(cwd.length + 1);
  209. }
  210. // return early if cached
  211. if (config.cache) {
  212. var callback = webpack.async();
  213. return cache(
  214. {
  215. directory: cacheDirectory,
  216. identifier: cacheIdentifier,
  217. options: config,
  218. source: input,
  219. transform: function() {
  220. return lint(engine, input, resourcePath);
  221. }
  222. },
  223. function(err, res) {
  224. if (err) {
  225. return callback(err);
  226. }
  227. try {
  228. printLinterOutput(
  229. assign({}, res || {}, { src: input }),
  230. config,
  231. webpack
  232. );
  233. } catch (e) {
  234. err = e;
  235. }
  236. return callback(err, input, map);
  237. }
  238. );
  239. }
  240. printLinterOutput(lint(engine, input, resourcePath), config, webpack);
  241. webpack.callback(null, input, map);
  242. };
  243. function lint(engine, input, resourcePath) {
  244. return engine.executeOnText(input, resourcePath, true);
  245. }