Skip to content

Commit bfa48c7

Browse files
authored
Merge pull request #935 from sheetalkamat/solutionBuilder
Using Solution builder to build project references
2 parents ab3ba29 + a47f244 commit bfa48c7

File tree

22 files changed

+608
-35
lines changed

22 files changed

+608
-35
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# Changelog
22

3+
## v6.1.0
4+
* [Build upstream project references with SolutionBuilder](https://github.com/TypeStrong/ts-loader/pull/935) (#851, #913) - thanks @sheetalkamat!
5+
36
## v6.0.4
47
* [Fix issue when handling files not included in tsconfig.json](https://github.com/TypeStrong/ts-loader/issues/943) (#934) - thanks @davazp!
58

README.md

Lines changed: 1 addition & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -569,33 +569,7 @@ This flag enables caching for some FS-functions like `fileExists`, `realpath` an
569569

570570
#### projectReferences _(boolean) (default=false)_
571571

572-
**TL;DR:** Using project references currently requires building referenced projects outside of ts-loader. We don’t want to keep it that way, but we’re releasing what we’ve got now. To try it out, you’ll need to pass `projectReferences: true` to `loaderOptions`. You’ll also probably need to use TypeScript 3.1.1 or later (which, as of this writing, means `typescript@next`).
573-
574-
ts-loader has partial support for [project references](https://www.typescriptlang.org/docs/handbook/project-references.html) in that it will _load_ dependent composite projects that are already built, but will not currently _build/rebuild_ those upstream projects. The best way to explain exactly what this means is through an example. Say you have a project with a project reference pointing to the `lib/` directory:
575-
576-
```
577-
tsconfig.json
578-
app.ts
579-
lib/
580-
tsconfig.json
581-
niftyUtil.ts
582-
```
583-
584-
And we’ll assume that the root `tsconfig.json` has `{ "references": { "path": "lib" } }`, which means that any import of a file that’s part of the `lib` sub-project is treated as a reference to another project, not just a reference to a TypeScript file. Before discussing how ts-loader handles this, it’s helpful to review at a really basic level what `tsc` itself does here. If you were to run `tsc` on this tiny example project, the build would fail with the error:
585-
586-
```
587-
error TS6305: Output file 'lib/niftyUtil.d.ts' has not been built from source file 'lib/niftyUtil.ts'.
588-
```
589-
590-
Using project references actually instructs `tsc` _not_ to build anything that’s part of another project from source, but rather to look for any `.d.ts` and `.js` files that have already been generated from a previous build. Since we’ve never built the project in `lib` before, those files don’t exist, so building the root project fails. Still just thinking about how `tsc` works, there are two options to make the build succeed: either run `tsc -p lib/tsconfig.json` _first_, or simply run `tsc --build`, which will figure out that `lib` hasn’t been built and build it first for you.
591-
592-
Ok, so how is that relevant to ts-loader? Because the best way to think about what ts-loader does with project references is that it acts like `tsc`, but _not_ like `tsc --build`. If you run ts-loader on a project that’s using project references, and any upstream project hasn’t been built, you’ll get the exact same `error TS6305` that you would get with `tsc`. If you modify a source file in an upstream project and don’t rebuild that project, `ts-loader` won’t have any idea that you’ve changed anything—it will still be looking at the output from the last time you _built_ that file.
593-
594-
**“Hey, don’t you think that sounds kind of useless and terrible?”** Well, sort of. You can consider it a work-in-progress. It’s true that on its own, as of today, ts-loader doesn’t have everything you need to take advantage of project references in webpack. In practice, though, _consuming_ upstream projects and _building_ upstream projects are somewhat separate concerns. Building them will likely come in a future release. For background, see the [original issue](https://github.com/TypeStrong/ts-loader/issues/815).
595-
596-
**`outDir` Windows problemo.** At the moment, composite projects built using the [`outDir` compiler option](https://www.typescriptlang.org/docs/handbook/compiler-options.html) cannot be consumed using ts-loader on Windows. If you try to, ts-loader throws a "has not been built from source file" error. We don't know why yet; it's possible there's a bug in `tsc`. It's more likely there's a bug in `ts-loader`. Hopefully it's going to get solved at some point. (Hey, maybe you're the one to solve it!) Either way, we didn't want to hold back from releasing. So if you're building on Windows then avoid building `composite` projects using `outDir`.
597-
598-
**TypeScript version compatibility.** As a final caveat, [this commit to TypeScript](https://github.com/Microsoft/TypeScript/commit/d519e3f21ec36274726c44dab25c9eb48e34953f) is necessary for the `include` or `exclude` options of a project-referenced tsconfig file to work. It should be released in TypeScript 3.1.1 according to the tags. To use an earlier version of TypeScript, referenced project configuration files must specify `files`, and not `include`.
572+
ts-loader has opt-in support for [project references](https://www.typescriptlang.org/docs/handbook/project-references.html). With this configuration option enabled, ts-loader will incrementally rebuild upstream projects the same way `tsc --build` does. Otherwise, source files in referenced projects will be treated as if they’re part of the root project.
599573

600574
### Usage with webpack watch
601575

package.json

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "ts-loader",
3-
"version": "6.0.4",
3+
"version": "6.1.0",
44
"description": "TypeScript loader for webpack",
55
"main": "index.js",
66
"types": "dist/types/index.d.ts",
@@ -9,8 +9,9 @@
99
"lint": "tslint --project \"./src\"",
1010
"comparison-tests": "tsc --project \"./test/comparison-tests\" && npm link ./test/comparison-tests/testLib && node test/comparison-tests/run-tests.js",
1111
"comparison-tests-generate": "node test/comparison-tests/stub-new-version.js",
12-
"execution-tests": "node test/execution-tests/run-tests.js",
13-
"test": "node test/run-tests.js",
12+
"execution-tests": "git clean -xfd test/execution-tests && node test/execution-tests/run-tests.js",
13+
"test": "git clean -xfd test/execution-tests && node test/run-tests.js",
14+
"clean": "git clean -xfd test/execution-tests",
1415
"docker:build": "docker build -t ts-loader .",
1516
"postdocker:build": "docker run -it ts-loader yarn test"
1617
},
@@ -88,7 +89,7 @@
8889
"rimraf": "^2.6.2",
8990
"tslint": "^5.11.0",
9091
"tslint-config-prettier": "^1.15.0",
91-
"typescript": "^3.5.2",
92+
"typescript": "^3.6.2",
9293
"webpack": "^4.5.0",
9394
"webpack-cli": "^3.1.1"
9495
},

src/compilerSetup.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,5 +70,13 @@ export function getCompilerOptions(
7070
compilerOptions.module = typescript.ModuleKind.CommonJS;
7171
}
7272

73+
if (configParseResult.options.configFile) {
74+
Object.defineProperty(compilerOptions, 'configFile', {
75+
enumerable: false,
76+
writable: false,
77+
value: configParseResult.options.configFile
78+
});
79+
}
80+
7381
return compilerOptions;
7482
}

src/config.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import * as semver from 'semver';
44
import * as typescript from 'typescript';
55
import * as webpack from 'webpack';
66

7+
import { getCompilerOptions } from './compilerSetup';
78
import { LoaderOptions, WebpackError } from './interfaces';
89
import * as logger from './logger';
910
import { formatErrors } from './utils';
@@ -149,3 +150,26 @@ export function getConfigParseResult(
149150

150151
return configParseResult;
151152
}
153+
154+
const extendedConfigCache = new Map() as typescript.Map<
155+
typescript.ExtendedConfigCacheEntry
156+
>;
157+
export function getParsedCommandLine(
158+
compiler: typeof typescript,
159+
loaderOptions: LoaderOptions,
160+
configFilePath: string
161+
): typescript.ParsedCommandLine | undefined {
162+
const result = compiler.getParsedCommandLineOfConfigFile(
163+
configFilePath,
164+
loaderOptions.compilerOptions,
165+
{
166+
...compiler.sys,
167+
onUnRecoverableConfigFileDiagnostic: () => {} // tslint:disable-line no-empty
168+
},
169+
extendedConfigCache
170+
);
171+
if (result) {
172+
result.options = getCompilerOptions(result);
173+
}
174+
return result;
175+
}

src/instances.ts

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,18 @@ import {
1717
WebpackError
1818
} from './interfaces';
1919
import * as logger from './logger';
20-
import { makeServicesHost, makeWatchHost } from './servicesHost';
20+
import {
21+
makeServicesHost,
22+
makeSolutionBuilderHost,
23+
makeWatchHost
24+
} from './servicesHost';
2125
import {
2226
appendSuffixesIfMatch,
2327
ensureProgram,
2428
formatErrors,
2529
isUsingProjectReferences,
26-
makeError
30+
makeError,
31+
supportsSolutionBuild
2732
} from './utils';
2833
import { makeWatchRun } from './watch-run';
2934

@@ -270,6 +275,23 @@ function successfulTypeScriptInstance(
270275
);
271276
}
272277

278+
if (configFilePath && supportsSolutionBuild(loaderOptions, compiler)) {
279+
// Use solution builder
280+
log.logInfo('Using SolutionBuilder api');
281+
instance.configFilePath = configFilePath;
282+
instance.solutionBuilderHost = makeSolutionBuilderHost(
283+
scriptRegex,
284+
log,
285+
loader,
286+
instance
287+
);
288+
instance.solutionBuilder = compiler.createSolutionBuilderWithWatch(
289+
instance.solutionBuilderHost,
290+
[configFilePath],
291+
{ verbose: true, watch: true }
292+
);
293+
}
294+
273295
if (loaderOptions.experimentalWatchApi && compiler.createWatchProgram) {
274296
log.logInfo('Using watch api');
275297

src/interfaces.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
export { ModuleResolutionHost } from 'typescript';
1+
export { ModuleResolutionHost, FormatDiagnosticsHost } from 'typescript';
22
import * as typescript from 'typescript';
33

44
import { Chalk } from 'chalk';
@@ -86,6 +86,14 @@ export interface TSInstance {
8686
program?: typescript.Program;
8787
hasUnaccountedModifiedFiles?: boolean;
8888
changedFilesList?: boolean;
89+
90+
solutionBuilderHost?: typescript.SolutionBuilderWithWatchHost<
91+
typescript.EmitAndSemanticDiagnosticsBuilderProgram
92+
>;
93+
solutionBuilder?: typescript.SolutionBuilder<
94+
typescript.EmitAndSemanticDiagnosticsBuilderProgram
95+
>;
96+
configFilePath?: string;
8997
}
9098

9199
export interface LoaderOptionsCache {

src/servicesHost.ts

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ import * as path from 'path';
22
import * as typescript from 'typescript';
33
import * as webpack from 'webpack';
44

5+
import { getParsedCommandLine } from './config';
56
import * as constants from './constants';
67
import {
78
CustomResolveModuleName,
89
CustomResolveTypeReferenceDirective,
10+
FormatDiagnosticsHost,
911
ModuleResolutionHost,
1012
ResolvedModule,
1113
ResolveSync,
@@ -508,6 +510,83 @@ export function makeWatchHost(
508510
}
509511
}
510512

513+
/**
514+
* Create the TypeScript Watch host
515+
*/
516+
export function makeSolutionBuilderHost(
517+
scriptRegex: RegExp,
518+
log: logger.Logger,
519+
loader: webpack.loader.LoaderContext,
520+
instance: TSInstance
521+
) {
522+
const {
523+
compiler,
524+
compilerOptions,
525+
appendTsTsxSuffixesIfRequired,
526+
loaderOptions: {
527+
resolveModuleName: customResolveModuleName,
528+
resolveTypeReferenceDirective: customResolveTypeReferenceDirective
529+
}
530+
} = instance;
531+
532+
// loader.context seems to work fine on Linux / Mac regardless causes problems for @types resolution on Windows for TypeScript < 2.3
533+
const getCurrentDirectory = () => loader.context;
534+
const formatDiagnosticHost: FormatDiagnosticsHost = {
535+
getCurrentDirectory: compiler.sys.getCurrentDirectory,
536+
getCanonicalFileName: compiler.sys.useCaseSensitiveFileNames
537+
? s => s
538+
: s => s.toLowerCase(),
539+
getNewLine: () => compiler.sys.newLine
540+
};
541+
542+
const reportDiagnostic = (d: typescript.Diagnostic) =>
543+
log.logError(compiler.formatDiagnostic(d, formatDiagnosticHost));
544+
const reportSolutionBuilderStatus = (d: typescript.Diagnostic) =>
545+
log.logInfo(compiler.formatDiagnostic(d, formatDiagnosticHost));
546+
const reportWatchStatus = (
547+
d: typescript.Diagnostic,
548+
newLine: string,
549+
_options: typescript.CompilerOptions
550+
) =>
551+
log.logInfo(
552+
`${compiler.flattenDiagnosticMessageText(
553+
d.messageText,
554+
compiler.sys.newLine
555+
)}${newLine + newLine}`
556+
);
557+
const solutionBuilderHost = compiler.createSolutionBuilderWithWatchHost(
558+
compiler.sys,
559+
compiler.createEmitAndSemanticDiagnosticsBuilderProgram,
560+
reportDiagnostic,
561+
reportSolutionBuilderStatus,
562+
reportWatchStatus
563+
);
564+
solutionBuilderHost.getCurrentDirectory = getCurrentDirectory;
565+
solutionBuilderHost.trace = logData => log.logInfo(logData);
566+
solutionBuilderHost.getParsedCommandLine = file =>
567+
getParsedCommandLine(compiler, instance.loaderOptions, file);
568+
569+
// make a (sync) resolver that follows webpack's rules
570+
const resolveSync = makeResolver(loader._compiler.options);
571+
const resolvers = makeResolvers(
572+
compiler,
573+
compilerOptions,
574+
solutionBuilderHost,
575+
customResolveTypeReferenceDirective,
576+
customResolveModuleName,
577+
resolveSync,
578+
appendTsTsxSuffixesIfRequired,
579+
scriptRegex,
580+
instance
581+
);
582+
// used for (/// <reference types="...">) see https://github.com/Realytics/fork-ts-checker-webpack-plugin/pull/250#issuecomment-485061329
583+
solutionBuilderHost.resolveTypeReferenceDirectives =
584+
resolvers.resolveTypeReferenceDirectives;
585+
solutionBuilderHost.resolveModuleNames = resolvers.resolveModuleNames;
586+
587+
return solutionBuilderHost;
588+
}
589+
511590
type ResolveTypeReferenceDirective = (
512591
directive: string,
513592
containingFile: string,

src/utils.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,9 @@ export function arrify<T>(val: T | T[]) {
235235
}
236236

237237
export function ensureProgram(instance: TSInstance) {
238+
if (instance.solutionBuilder) {
239+
instance.solutionBuilder.buildReferences(instance.configFilePath!);
240+
}
238241
if (instance && instance.watchHost) {
239242
if (instance.hasUnaccountedModifiedFiles) {
240243
if (instance.changedFilesList) {
@@ -351,6 +354,13 @@ export function validateSourceMapOncePerProject(
351354
}
352355
}
353356

357+
export function supportsSolutionBuild(
358+
loaderOptions: LoaderOptions,
359+
compiler: typeof typescript
360+
) {
361+
return !!loaderOptions.projectReferences && !!compiler.InvalidatedProjectKind;
362+
}
363+
354364
/**
355365
* Gets the output JS file path for an input file governed by a composite project.
356366
* Pulls from the cache if it exists; computes and caches the result otherwise.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/* eslint-disable no-var, strict */
2+
'use strict';
3+
var webpackConfig = require('./webpack.config.js');
4+
var makeKarmaConfig = require('../../karmaConfig');
5+
6+
module.exports = function(config) {
7+
config.set(
8+
makeKarmaConfig({
9+
config,
10+
webpackConfig,
11+
files: [
12+
// This ensures we have the es6 shims in place from babel and then loads all the tests
13+
'main.js'
14+
]
15+
})
16+
);
17+
};
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
*.d.ts
2+
*.js
3+
*.js.map
4+
*.tsbuildinfo
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export const lib = {
2+
one: 1,
3+
two: 2,
4+
three: 3
5+
};
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"compilerOptions": {
3+
"composite": true,
4+
"sourceMap": true
5+
},
6+
"files": [
7+
"./index.ts"
8+
]
9+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
const testsContext = require.context('./', true, /\.tests\.ts(x?)$/);
2+
testsContext.keys().forEach(testsContext);
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"name": "basic",
3+
"license": "MIT",
4+
"version": "1.0.0",
5+
"main": "index.js",
6+
"devDependencies": {
7+
"@types/jasmine": "^2.5.35",
8+
"jasmine-core": "^2.3.4"
9+
}
10+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { lib } from '../lib';
2+
3+
export function whatNumbersDoYouHave() {
4+
return [lib.one, lib.two, lib.three];
5+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { whatNumbersDoYouHave } from "../src/app";
2+
3+
describe("app", () => {
4+
it("code compiles referenced project", () => {
5+
expect(whatNumbersDoYouHave()).toEqual([1, 2, 3]);
6+
});
7+
});
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"files": [
3+
"./src/app.ts"
4+
],
5+
"references": [
6+
{ "path": "./lib" }
7+
],
8+
"compilerOptions": {
9+
"noEmitOnError": true
10+
}
11+
}

0 commit comments

Comments
 (0)