Skip to content

feat: add support for "generateTrace" tsconfig option #523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,20 @@ npm install --save-dev @types/webpack
yarn add --dev @types/webpack
```

## Profiling types resolution

Starting from TypeScript 4.1.0 (currently in beta), you can profile long type checks by
setting "generateTrace" compiler option. This is an instruction from [microsoft/TypeScript#40063](https://github.com/microsoft/TypeScript/pull/40063):

1. Set "generateTrace": "{folderName}" in your `tsconfig.json`
2. Look in the resulting folder. If you used build mode, there will be a `legend.json` telling you what went where.
Otherwise, there will be `trace.json` file and `types.json` files.
3. Navigate to [edge://tracing](edge://tracing) or [chrome://tracing](chrome://tracing) and load `trace.json`
4. Expand Process 1 with the little triangle in the left sidebar
5. Click on different blocks to see their payloads in the bottom pane
6. Open `types.json` in an editor
7. When you see a type ID in the tracing output, go-to-line {id} to find data about that type


## Related projects

Expand Down
117 changes: 107 additions & 10 deletions src/typescript-reporter/reporter/TypeScriptReporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ import {
import { createPerformance } from '../../profile/Performance';
import { connectTypeScriptPerformance } from '../profile/TypeScriptPerformance';

// write this type as it's available only in the newest TypeScript versions (^4.1.0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So when typescript 4.1 ships we can lose this?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We would have to upgrade typescript in dev dependencies, and then probably this type will be available (if it will be in the public API)

interface Tracing {
startTracing(configFilePath: string, traceDirPath: string, isBuildMode: boolean): void;
stopTracing(typeCatalog: unknown): void;
dumpLegend(): void;
}

function createTypeScriptReporter(configuration: TypeScriptReporterConfiguration): Reporter {
let parsedConfiguration: ts.ParsedCommandLine | undefined;
let parseConfigurationDiagnostics: ts.Diagnostic[] = [];
Expand Down Expand Up @@ -49,8 +56,17 @@ function createTypeScriptReporter(configuration: TypeScriptReporterConfiguration
extensions.push(createTypeScriptVueExtension(configuration.extensions.vue));
}

function getConfigFilePathFromCompilerOptions(compilerOptions: ts.CompilerOptions): string {
return (compilerOptions.configFilePath as unknown) as string;
}

function getProjectNameOfBuilderProgram(builderProgram: ts.BuilderProgram): string {
return (builderProgram.getProgram().getCompilerOptions().configFilePath as unknown) as string;
return getConfigFilePathFromCompilerOptions(builderProgram.getProgram().getCompilerOptions());
}

function getTracing(): Tracing | undefined {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (typescript as any).tracing;
}

function getDiagnosticsOfBuilderProgram(builderProgram: ts.BuilderProgram) {
Expand Down Expand Up @@ -152,6 +168,49 @@ function createTypeScriptReporter(configuration: TypeScriptReporterConfiguration
);
}

function startProfilingIfNeeded() {
if (configuration.profile) {
performance.enable();
}
}

function stopProfilingIfNeeded() {
if (configuration.profile) {
performance.print();
performance.disable();
}
}

function startTracingIfNeeded(compilerOptions: ts.CompilerOptions) {
const tracing = getTracing();

if (compilerOptions.generateTrace && tracing) {
tracing.startTracing(
getConfigFilePathFromCompilerOptions(compilerOptions),
compilerOptions.generateTrace as string,
configuration.build
);
}
}

function stopTracingIfNeeded(program: ts.BuilderProgram) {
const tracing = getTracing();
const compilerOptions = program.getCompilerOptions();

if (compilerOptions.generateTrace && tracing) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
tracing.stopTracing((program.getProgram() as any).getTypeCatalog());
}
}

function dumpTracingLegendIfNeeded() {
const tracing = getTracing();

if (tracing) {
tracing.dumpLegend();
}
}

return {
getReport: async ({ changedFiles = [], deletedFiles = [] }) => {
// clear cache to be ready for next iteration and to free memory
Expand Down Expand Up @@ -227,9 +286,7 @@ function createTypeScriptReporter(configuration: TypeScriptReporterConfiguration
return dependencies;
},
async getIssues() {
if (configuration.profile) {
performance.enable();
}
startProfilingIfNeeded();

parsedConfiguration = parseConfigurationIfNeeded();

Expand Down Expand Up @@ -261,7 +318,26 @@ function createTypeScriptReporter(configuration: TypeScriptReporterConfiguration
typescript,
parsedConfiguration,
system,
typescript.createSemanticDiagnosticsBuilderProgram,
(
rootNames,
compilerOptions,
host,
oldProgram,
configFileParsingDiagnostics,
projectReferences
) => {
if (compilerOptions) {
startTracingIfNeeded(compilerOptions);
}
return typescript.createSemanticDiagnosticsBuilderProgram(
rootNames,
compilerOptions,
host,
oldProgram,
configFileParsingDiagnostics,
projectReferences
);
},
undefined,
undefined,
undefined,
Expand All @@ -275,6 +351,8 @@ function createTypeScriptReporter(configuration: TypeScriptReporterConfiguration

// emit .tsbuildinfo file if needed
emitTsBuildInfoFileForBuilderProgram(builderProgram);

stopTracingIfNeeded(builderProgram);
},
extensions
);
Expand Down Expand Up @@ -308,7 +386,26 @@ function createTypeScriptReporter(configuration: TypeScriptReporterConfiguration
typescript,
parsedConfiguration,
system,
typescript.createSemanticDiagnosticsBuilderProgram,
(
rootNames,
compilerOptions,
host,
oldProgram,
configFileParsingDiagnostics,
projectReferences
) => {
if (compilerOptions) {
startTracingIfNeeded(compilerOptions);
}
return typescript.createSemanticDiagnosticsBuilderProgram(
rootNames,
compilerOptions,
host,
oldProgram,
configFileParsingDiagnostics,
projectReferences
);
},
undefined,
undefined,
(builderProgram) => {
Expand All @@ -320,6 +417,8 @@ function createTypeScriptReporter(configuration: TypeScriptReporterConfiguration

// emit .tsbuildinfo file if needed
emitTsBuildInfoFileForBuilderProgram(builderProgram);

stopTracingIfNeeded(builderProgram);
},
extensions
);
Expand Down Expand Up @@ -370,10 +469,8 @@ function createTypeScriptReporter(configuration: TypeScriptReporterConfiguration
}
});

if (configuration.profile) {
performance.print();
performance.disable();
}
dumpTracingLegendIfNeeded();
stopProfilingIfNeeded();

return issues;
},
Expand Down
92 changes: 92 additions & 0 deletions test/e2e/TypeScriptGenerateTrace.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { readFixture } from './sandbox/Fixture';
import { join } from 'path';
import { createSandbox, Sandbox } from './sandbox/Sandbox';
import {
createWebpackDevServerDriver,
WEBPACK_CLI_VERSION,
WEBPACK_DEV_SERVER_VERSION,
} from './sandbox/WebpackDevServerDriver';
import { FORK_TS_CHECKER_WEBPACK_PLUGIN_VERSION } from './sandbox/Plugin';

describe('TypeScript Generate Trace', () => {
let sandbox: Sandbox;

beforeAll(async () => {
sandbox = await createSandbox();
});

beforeEach(async () => {
await sandbox.reset();
});

afterAll(async () => {
await sandbox.cleanup();
});

it('generates trace for typescript 4.1.0-beta in watch mode', async () => {
await sandbox.load([
await readFixture(join(__dirname, 'fixtures/environment/typescript-basic.fixture'), {
FORK_TS_CHECKER_WEBPACK_PLUGIN_VERSION: JSON.stringify(
FORK_TS_CHECKER_WEBPACK_PLUGIN_VERSION
),
TS_LOADER_VERSION: JSON.stringify('^7.0.0'),
TYPESCRIPT_VERSION: JSON.stringify('4.1.0-beta'),
WEBPACK_VERSION: JSON.stringify('^4.0.0'),
WEBPACK_CLI_VERSION: JSON.stringify(WEBPACK_CLI_VERSION),
WEBPACK_DEV_SERVER_VERSION: JSON.stringify(WEBPACK_DEV_SERVER_VERSION),
ASYNC: JSON.stringify(true),
}),
await readFixture(join(__dirname, 'fixtures/implementation/typescript-basic.fixture')),
]);

// update sandbox to generate trace
await sandbox.patch(
'tsconfig.json',
' "outDir": "./dist"',
[' "outDir": "./dist",', ' "generateTrace": "./traces"'].join('\n')
);

const driver = createWebpackDevServerDriver(sandbox.spawn('npm run webpack-dev-server'), true);

// first compilation is successful
await driver.waitForNoErrors();

expect(await sandbox.exists('traces/trace.json')).toBe(true);
expect(await sandbox.exists('traces/types.json')).toBe(true);
});

it('generates trace for typescript 4.1.0-beta in build mode', async () => {
await sandbox.load([
await readFixture(join(__dirname, 'fixtures/environment/typescript-monorepo.fixture'), {
FORK_TS_CHECKER_WEBPACK_PLUGIN_VERSION: JSON.stringify(
FORK_TS_CHECKER_WEBPACK_PLUGIN_VERSION
),
TYPESCRIPT_VERSION: JSON.stringify('4.1.0-beta'),
WEBPACK_VERSION: JSON.stringify('^4.0.0'),
WEBPACK_CLI_VERSION: JSON.stringify(WEBPACK_CLI_VERSION),
WEBPACK_DEV_SERVER_VERSION: JSON.stringify(WEBPACK_DEV_SERVER_VERSION),
ASYNC: JSON.stringify(true),
MODE: JSON.stringify('readonly'),
}),
await readFixture(join(__dirname, 'fixtures/implementation/typescript-monorepo.fixture')),
]);

// update sandbox to generate trace
await sandbox.patch(
'tsconfig.json',
' "rootDir": "./packages"',
[' "rootDir": "./packages",', ' "generateTrace": "./traces"'].join('\n')
);

const driver = createWebpackDevServerDriver(sandbox.spawn('npm run webpack-dev-server'), true);

// first compilation is successful
await driver.waitForNoErrors();

expect(await sandbox.exists('traces/trace.1.json')).toBe(true);
expect(await sandbox.exists('traces/types.1.json')).toBe(true);
expect(await sandbox.exists('traces/trace.2.json')).toBe(true);
expect(await sandbox.exists('traces/types.2.json')).toBe(true);
expect(await sandbox.exists('traces/legend.json')).toBe(true);
});
});
Loading