after-compile.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.makeAfterCompile = void 0;
  4. const path = require("path");
  5. const webpack = require("webpack");
  6. const constants = require("./constants");
  7. const instances_1 = require("./instances");
  8. const utils_1 = require("./utils");
  9. /**
  10. * This returns a function that has options to add assets and also to provide errors to webpack
  11. * In webpack 4 we can do both during the afterCompile hook
  12. * In webpack 5 only errors should be provided during aftercompile. Assets should be
  13. * emitted during the afterProcessAssets hook
  14. */
  15. function makeAfterCompile(instance, configFilePath) {
  16. let getCompilerOptionDiagnostics = true;
  17. let checkAllFilesForErrors = true;
  18. return (compilation, callback) => {
  19. // Don't add errors for child compilations
  20. if (compilation.compiler.isChild()) {
  21. callback();
  22. return;
  23. }
  24. if (instance.loaderOptions.transpileOnly) {
  25. provideAssetsFromSolutionBuilderHost(instance, compilation);
  26. callback();
  27. return;
  28. }
  29. removeCompilationTSLoaderErrors(compilation, instance.loaderOptions);
  30. provideCompilerOptionDiagnosticErrorsToWebpack(getCompilerOptionDiagnostics, compilation, instance, configFilePath);
  31. getCompilerOptionDiagnostics = false;
  32. const modules = determineModules(compilation, instance);
  33. const filesToCheckForErrors = determineFilesToCheckForErrors(checkAllFilesForErrors, instance);
  34. checkAllFilesForErrors = false;
  35. const filesWithErrors = new Map();
  36. provideErrorsToWebpack(filesToCheckForErrors, filesWithErrors, compilation, modules, instance);
  37. provideSolutionErrorsToWebpack(compilation, modules, instance);
  38. provideDeclarationFilesToWebpack(filesToCheckForErrors, instance, compilation);
  39. provideTsBuildInfoFilesToWebpack(instance, compilation);
  40. provideAssetsFromSolutionBuilderHost(instance, compilation);
  41. instance.filesWithErrors = filesWithErrors;
  42. instance.modifiedFiles = undefined;
  43. instance.projectsMissingSourceMaps = new Set();
  44. callback();
  45. };
  46. }
  47. exports.makeAfterCompile = makeAfterCompile;
  48. /**
  49. * handle compiler option errors after the first compile
  50. */
  51. function provideCompilerOptionDiagnosticErrorsToWebpack(getCompilerOptionDiagnostics, compilation, instance, configFilePath) {
  52. if (getCompilerOptionDiagnostics) {
  53. const { languageService, loaderOptions, compiler, program } = instance;
  54. const errors = (0, utils_1.formatErrors)(program === undefined
  55. ? languageService.getCompilerOptionsDiagnostics()
  56. : program.getOptionsDiagnostics(), loaderOptions, instance.colors, compiler, { file: configFilePath || 'tsconfig.json' }, compilation.compiler.context);
  57. compilation.errors.push(...errors);
  58. }
  59. }
  60. /**
  61. * build map of all modules based on normalized filename
  62. * this is used for quick-lookup when trying to find modules
  63. * based on filepath
  64. */
  65. function determineModules(compilation, { filePathKeyMapper }) {
  66. const modules = new Map();
  67. compilation.modules.forEach(module => {
  68. if (module instanceof webpack.NormalModule && module.resource) {
  69. const modulePath = filePathKeyMapper(module.resource);
  70. const existingModules = modules.get(modulePath);
  71. if (existingModules !== undefined) {
  72. if (!existingModules.includes(module)) {
  73. existingModules.push(module);
  74. }
  75. }
  76. else {
  77. modules.set(modulePath, [module]);
  78. }
  79. }
  80. });
  81. return modules;
  82. }
  83. function determineFilesToCheckForErrors(checkAllFilesForErrors, instance) {
  84. const { files, modifiedFiles, filesWithErrors, otherFiles } = instance;
  85. // calculate array of files to check
  86. const filesToCheckForErrors = new Map();
  87. if (checkAllFilesForErrors) {
  88. // check all files on initial run
  89. for (const [filePath, file] of files) {
  90. addFileToCheckForErrors(filePath, file);
  91. }
  92. for (const [filePath, file] of otherFiles) {
  93. addFileToCheckForErrors(filePath, file);
  94. }
  95. }
  96. else if (modifiedFiles !== null &&
  97. modifiedFiles !== undefined &&
  98. modifiedFiles.size) {
  99. const reverseDependencyGraph = (0, utils_1.populateReverseDependencyGraph)(instance);
  100. // check all modified files, and all dependants
  101. for (const modifiedFileName of modifiedFiles.keys()) {
  102. for (const fileName of (0, utils_1.collectAllDependants)(reverseDependencyGraph, modifiedFileName).keys()) {
  103. const fileToCheckForErrors = files.get(fileName) || otherFiles.get(fileName);
  104. if (fileToCheckForErrors) { //file may have been removed
  105. addFileToCheckForErrors(fileName, fileToCheckForErrors);
  106. }
  107. }
  108. }
  109. }
  110. // re-check files with errors from previous build
  111. if (filesWithErrors !== undefined) {
  112. for (const [fileWithErrorName, fileWithErrors] of filesWithErrors) {
  113. addFileToCheckForErrors(fileWithErrorName, fileWithErrors);
  114. }
  115. }
  116. return filesToCheckForErrors;
  117. function addFileToCheckForErrors(filePath, file) {
  118. if (file && !(0, utils_1.isReferencedFile)(instance, filePath)) {
  119. filesToCheckForErrors.set(filePath, file);
  120. }
  121. }
  122. }
  123. function provideErrorsToWebpack(filesToCheckForErrors, filesWithErrors, compilation, modules, instance) {
  124. const { compiler, files, loaderOptions, compilerOptions, otherFiles, } = instance;
  125. const filePathRegex = compilerOptions.allowJs === true
  126. ? constants.dtsTsTsxJsJsxRegex
  127. : constants.dtsTsTsxRegex;
  128. // I’m pretty sure this will never be undefined here
  129. const program = (0, utils_1.ensureProgram)(instance);
  130. for (const [filePath, { fileName }] of filesToCheckForErrors.entries()) {
  131. if (fileName.match(filePathRegex) === null) {
  132. continue;
  133. }
  134. const sourceFile = program && program.getSourceFile(fileName);
  135. const errors = [];
  136. if (program && sourceFile) {
  137. errors.push(...program.getSyntacticDiagnostics(sourceFile), ...program
  138. .getSemanticDiagnostics(sourceFile)
  139. // Output file has not been built from source file - this message is redundant with
  140. // program.getOptionsDiagnostics() separately added in instances.ts
  141. .filter(({ code }) => code !== 6305));
  142. }
  143. if (errors.length > 0) {
  144. const fileWithError = files.get(filePath) || otherFiles.get(filePath);
  145. filesWithErrors.set(filePath, fileWithError);
  146. }
  147. // if we have access to a webpack module, use that
  148. const associatedModules = modules.get(instance.filePathKeyMapper(fileName));
  149. if (associatedModules !== undefined) {
  150. associatedModules.forEach(module => {
  151. removeModuleTSLoaderError(module, loaderOptions);
  152. // append errors
  153. const formattedErrors = (0, utils_1.formatErrors)(errors, loaderOptions, instance.colors, compiler, { module }, compilation.compiler.context);
  154. formattedErrors.forEach(error => {
  155. if (module.addError) {
  156. module.addError(error);
  157. }
  158. else {
  159. module.errors.push(error);
  160. }
  161. });
  162. compilation.errors.push(...formattedErrors);
  163. });
  164. }
  165. else {
  166. // otherwise it's a more generic error
  167. const formattedErrors = (0, utils_1.formatErrors)(errors, loaderOptions, instance.colors, compiler, { file: fileName }, compilation.compiler.context);
  168. compilation.errors.push(...formattedErrors);
  169. }
  170. }
  171. }
  172. function provideSolutionErrorsToWebpack(compilation, modules, instance) {
  173. if (!instance.solutionBuilderHost ||
  174. !(instance.solutionBuilderHost.diagnostics.global.length ||
  175. instance.solutionBuilderHost.diagnostics.perFile.size)) {
  176. return;
  177. }
  178. const { compiler, loaderOptions, solutionBuilderHost: { diagnostics }, } = instance;
  179. for (const [filePath, perFileDiagnostics] of diagnostics.perFile) {
  180. // if we have access to a webpack module, use that
  181. const associatedModules = modules.get(filePath);
  182. if (associatedModules !== undefined) {
  183. associatedModules.forEach(module => {
  184. removeModuleTSLoaderError(module, loaderOptions);
  185. // append errors
  186. const formattedErrors = (0, utils_1.formatErrors)(perFileDiagnostics, loaderOptions, instance.colors, compiler, { module }, compilation.compiler.context);
  187. formattedErrors.forEach(error => {
  188. if (module.addError) {
  189. module.addError(error);
  190. }
  191. else {
  192. module.errors.push(error);
  193. }
  194. });
  195. compilation.errors.push(...formattedErrors);
  196. });
  197. }
  198. else {
  199. // otherwise it's a more generic error
  200. const formattedErrors = (0, utils_1.formatErrors)(perFileDiagnostics, loaderOptions, instance.colors, compiler, { file: path.resolve(perFileDiagnostics[0].file.fileName) }, compilation.compiler.context);
  201. compilation.errors.push(...formattedErrors);
  202. }
  203. }
  204. // Add global solution errors
  205. compilation.errors.push(...(0, utils_1.formatErrors)(diagnostics.global, instance.loaderOptions, instance.colors, instance.compiler, { file: 'tsconfig.json' }, compilation.compiler.context));
  206. }
  207. /**
  208. * gather all declaration files from TypeScript and output them to webpack.
  209. * JavaScript declaration files are included if `allowJs` is set.
  210. */
  211. function provideDeclarationFilesToWebpack(filesToCheckForErrors, instance, compilation) {
  212. const filePathRegex = instance.compilerOptions.allowJs === true
  213. ? constants.dtsTsTsxJsJsxRegex
  214. : constants.dtsTsTsxRegex;
  215. for (const { fileName } of filesToCheckForErrors.values()) {
  216. if (fileName.match(filePathRegex) === null) {
  217. continue;
  218. }
  219. addDeclarationFilesAsAsset((0, instances_1.getEmitOutput)(instance, fileName), compilation);
  220. }
  221. }
  222. function addDeclarationFilesAsAsset(outputFiles, compilation, skipOutputFile) {
  223. outputFilesToAsset(outputFiles, compilation, outputFile => skipOutputFile && skipOutputFile(outputFile)
  224. ? true
  225. : !outputFile.name.match(constants.dtsDtsxOrDtsDtsxMapRegex));
  226. }
  227. function outputFileToAsset(outputFile, compilation) {
  228. const assetPath = path
  229. .relative(compilation.compiler.outputPath, outputFile.name)
  230. // According to @alexander-akait (and @sokra) we should always '/' https://github.com/TypeStrong/ts-loader/pull/1251#issuecomment-799606985
  231. .replace(/\\/g, '/');
  232. // As suggested by @JonWallsten here: https://github.com/TypeStrong/ts-loader/pull/1251#issuecomment-800032753
  233. compilation.emitAsset(assetPath, new webpack.sources.RawSource(outputFile.text));
  234. }
  235. function outputFilesToAsset(outputFiles, compilation, skipOutputFile) {
  236. for (const outputFile of outputFiles) {
  237. if (!skipOutputFile || !skipOutputFile(outputFile)) {
  238. outputFileToAsset(outputFile, compilation);
  239. }
  240. }
  241. }
  242. /**
  243. * gather all .tsbuildinfo for the project
  244. */
  245. function provideTsBuildInfoFilesToWebpack(instance, compilation) {
  246. if (instance.watchHost) {
  247. // Ensure emit is complete
  248. (0, instances_1.getEmitFromWatchHost)(instance);
  249. if (instance.watchHost.tsbuildinfo) {
  250. outputFileToAsset(instance.watchHost.tsbuildinfo, compilation);
  251. }
  252. instance.watchHost.outputFiles.clear();
  253. instance.watchHost.tsbuildinfo = undefined;
  254. }
  255. }
  256. /**
  257. * gather all solution builder assets
  258. */
  259. function provideAssetsFromSolutionBuilderHost(instance, compilation) {
  260. if (instance.solutionBuilderHost) {
  261. // written files
  262. outputFilesToAsset(instance.solutionBuilderHost.writtenFiles, compilation);
  263. instance.solutionBuilderHost.writtenFiles.length = 0;
  264. }
  265. }
  266. /**
  267. * handle all other errors. The basic approach here to get accurate error
  268. * reporting is to start with a "blank slate" each compilation and gather
  269. * all errors from all files. Since webpack tracks errors in a module from
  270. * compilation-to-compilation, and since not every module always runs through
  271. * the loader, we need to detect and remove any pre-existing errors.
  272. */
  273. function removeCompilationTSLoaderErrors(compilation, loaderOptions) {
  274. compilation.errors = compilation.errors.filter(error => error.details !== (0, utils_1.tsLoaderSource)(loaderOptions));
  275. }
  276. function removeModuleTSLoaderError(module, loaderOptions) {
  277. const warnings = module.getWarnings();
  278. const errors = module.getErrors();
  279. module.clearWarningsAndErrors();
  280. Array.from(warnings || []).forEach(warning => module.addWarning(warning));
  281. Array.from(errors || [])
  282. .filter((error) => error.loaderSource !== (0, utils_1.tsLoaderSource)(loaderOptions))
  283. .forEach(error => module.addError(error));
  284. }
  285. //# sourceMappingURL=after-compile.js.map