Skip to content
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

Added support for updating tsconfig.json when using astro add #4959

Merged
merged 8 commits into from
Oct 12, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions .changeset/giant-news-speak.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': minor
---

Added support for updating TypeScript settings automatically when using `astro add`
Copy link
Contributor

Choose a reason for hiding this comment

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

Would you mind expanding this description a bit more into like a paragraph so it can be copy/pasted into a release blog post? Thanks!

Copy link
Member Author

Choose a reason for hiding this comment

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

Sure, let me do that

1 change: 1 addition & 0 deletions packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@
"@types/yargs-parser": "^21.0.0",
"boxen": "^6.2.1",
"ci-info": "^3.3.1",
"comment-json": "^4.2.3",
"common-ancestor-path": "^1.0.1",
"cookie": "^0.5.0",
"debug": "^4.3.4",
Expand Down
210 changes: 185 additions & 25 deletions packages/astro/src/core/add/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import type { AstroTelemetry } from '@astrojs/telemetry';
import boxen from 'boxen';
import { assign, parse as parseJSON, stringify } from 'comment-json';
import { diffWords } from 'diff';
import { execa } from 'execa';
import { existsSync, promises as fs } from 'fs';
import { bold, cyan, dim, green, magenta, yellow } from 'kleur/colors';
import { bold, cyan, dim, green, magenta, red, yellow } from 'kleur/colors';
import ora from 'ora';
import path from 'path';
import preferredPM from 'preferred-pm';
import prompts from 'prompts';
import type { TsConfigJson } from 'tsconfig-resolver';
import { fileURLToPath, pathToFileURL } from 'url';
import type yargs from 'yargs-parser';
import { resolveConfigPath } from '../config/index.js';
import { loadTSConfig, resolveConfigPath } from '../config/index.js';
import { debug, info, LogOptions } from '../logger/core.js';
import * as msg from '../messages.js';
import { printHelp } from '../messages.js';
Expand All @@ -19,6 +21,7 @@ import { apply as applyPolyfill } from '../polyfill.js';
import { parseNpmName } from '../util.js';
import { generate, parse, t, visit } from './babel.js';
import { ensureImport } from './imports.js';
import { tsconfigsPresets } from './tsconfigs.js';
import { wrapDefaultExport } from './wrapper.js';

export interface AddOptions {
Expand Down Expand Up @@ -239,7 +242,7 @@ export default async function add(names: string[], { cwd, flags, logging, teleme
switch (configResult) {
case UpdateResult.cancelled: {
info(logging, null, msg.cancelled(`Your configuration has ${bold('NOT')} been updated.`));
return;
break;
}
case UpdateResult.none: {
const pkgURL = new URL('./package.json', configURL);
Expand All @@ -253,12 +256,12 @@ export default async function add(names: string[], { cwd, flags, logging, teleme
);
if (missingDeps.length === 0) {
info(logging, null, msg.success(`Configuration up-to-date.`));
return;
break;
}
}

info(logging, null, msg.success(`Configuration up-to-date.`));
return;
break;
}
default: {
const list = integrations.map((integration) => ` - ${integration.packageName}`).join('\n');
Expand All @@ -273,6 +276,30 @@ export default async function add(names: string[], { cwd, flags, logging, teleme
);
}
}

let updateTSConfigResult: UpdateResult | undefined;
try {
updateTSConfigResult = await updateTSConfig(cwd, logging, integrations, flags);
} catch (err) {
debug('add', 'Error updating tsconfig.json', err);
throw createPrettyError(err as Error);
}

switch (updateTSConfigResult) {
case UpdateResult.none: {
Copy link
Contributor

Choose a reason for hiding this comment

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

love it

break;
}
case UpdateResult.cancelled: {
info(
logging,
null,
msg.cancelled(`Your TypeScript configuration has ${bold('NOT')} been updated.`)
);
break;
}
default:
info(logging, null, msg.success(`Successfully updated TypeScript settings`));
}
}

function isAdapter(
Expand Down Expand Up @@ -471,29 +498,13 @@ async function updateAstroConfig({
return UpdateResult.none;
}

let changes = [];
for (const change of diffWords(input, output)) {
let lines = change.value.trim().split('\n').slice(0, change.count);
if (lines.length === 0) continue;
if (change.added) {
if (!change.value.trim()) continue;
changes.push(change.value);
}
}
if (changes.length === 0) {
return UpdateResult.none;
}
const diff = getDiffContent(input, output);

let diffed = output;
for (let newContent of changes) {
const coloredOutput = newContent
.split('\n')
.map((ln) => (ln ? green(ln) : ''))
.join('\n');
diffed = diffed.replace(newContent, coloredOutput);
if (!diff) {
return UpdateResult.none;
}

const message = `\n${boxen(diffed, {
const message = `\n${boxen(diff, {
margin: 0.5,
padding: 0.5,
borderStyle: 'round',
Expand Down Expand Up @@ -533,6 +544,7 @@ interface InstallCommand {
flags: string[];
dependencies: string[];
}

async function getInstallIntegrationsCommand({
integrations,
cwd = process.cwd(),
Expand Down Expand Up @@ -727,6 +739,128 @@ export async function validateIntegrations(integrations: string[]): Promise<Inte
}
}

async function updateTSConfig(
Princesseuh marked this conversation as resolved.
Show resolved Hide resolved
cwd = process.cwd(),
logging: LogOptions,
integrationsInfo: IntegrationInfo[],
flags: yargs.Arguments
): Promise<UpdateResult> {
const frameworkWithTSSettings = ['solid-js', 'preact', 'react', 'vue'] as const;
Princesseuh marked this conversation as resolved.
Show resolved Hide resolved
const integrations = integrationsInfo.map(
(integration) => integration.id as 'solid-js' | 'preact' | 'react' | 'vue'
);
const firstIntegrationWithTSSettings = integrations.find((integration) =>
frameworkWithTSSettings.includes(integration)
);

if (!firstIntegrationWithTSSettings) {
return UpdateResult.none;
}

let inputConfig = loadTSConfig(cwd);
Princesseuh marked this conversation as resolved.
Show resolved Hide resolved
const configFileName = inputConfig?.path ? inputConfig.path.split('/').pop() : 'tsconfig.json';

if (inputConfig?.reason === 'invalid-config') {
throw new Error(
`Unknown error parsing ${configFileName}. Your ${configFileName} is most likely invalid`
);
}

let baseConfig = {};
if (!inputConfig || inputConfig.reason === 'not-found') {
debug('add', `Couldn't find ts/jsconfig.json, generating one`);
Princesseuh marked this conversation as resolved.
Show resolved Hide resolved
baseConfig = { extends: 'astro/tsconfigs/base' };
}

const parsedConfig = inputConfig?.path
? parseJSON((await fs.readFile(inputConfig.path)).toString())
: {};

const input = inputConfig?.path ? stringify(parsedConfig, null, 2) : '';

const outputConfig = assign<TsConfigJson, TsConfigJson>(parsedConfig ?? {}, {
...baseConfig,
...(tsconfigsPresets[firstIntegrationWithTSSettings] as TsConfigJson), // Cast needed because `tsconfig-resolver`'s types are outdated
});

if (inputConfig === outputConfig) {
return UpdateResult.none;
}

const output = stringify(outputConfig, null, 2);
const diff = getDiffContent(input, output);

if (!diff) {
return UpdateResult.none;
}

const message = `\n${boxen(diff, {
margin: 0.5,
padding: 0.5,
borderStyle: 'round',
title: configFileName,
})}\n`;

// Every major framework, apart from Vue and Svelte requires different `jsxImportSource`, as such it's impossible to config
// all of them in the same `tsconfig.json`. However, Vue only need `"jsx": "preserve"` for template intellisense which
// can be compatible with some frameworks (ex: Solid), though ultimately run into issues on the current version of Volar
const conflictingIntegrations = [
...Object.keys(tsconfigsPresets).filter((config) => config !== 'vue'),
];
const hasConflictingIntegrations =
integrations.filter((integration) => frameworkWithTSSettings.includes(integration)).length >
1 &&
integrations.filter((integration) => conflictingIntegrations.includes(integration)).length > 0;

info(
logging,
null,
`\n ${magenta(`Astro will make the following changes to your ${configFileName}:`)}\n${message}`
);

if (hasConflictingIntegrations) {
info(
logging,
null,
red(
` ${bold(
'Caution:'
)} Selected UI frameworks require conflicting tsconfig.json settings, as such only settings for ${bold(
firstIntegrationWithTSSettings
)} were used.\n More information: https://docs.astro.build/en/guides/typescript/#errors-typing-multiple-jsx-frameworks-at-the-same-time\n`
)
);
}

if (
integrations.includes('vue') &&
hasConflictingIntegrations &&
((outputConfig.compilerOptions?.jsx !== 'preserve' &&
(outputConfig as any).compilerOptions['jsxImportSource'] !== undefined) ||
integrations.includes('react')) // https://docs.astro.build/en/guides/typescript/#vue-components-are-mistakenly-typed-by-the-typesreact-package-when-installed
) {
info(
logging,
null,
red(
` ${bold(
'Caution:'
)} Using Vue together with a JSX framework can lead to type checking issues inside Vue files.\n More information: https://docs.astro.build/en/guides/typescript/#vue-components-are-mistakenly-typed-by-the-typesreact-package-when-installed\n`
)
);
}

if (await askToContinue({ flags })) {
await fs.writeFile(inputConfig?.path ?? path.join(cwd, 'tsconfig.json'), output, {
Princesseuh marked this conversation as resolved.
Show resolved Hide resolved
encoding: 'utf-8',
});
debug('add', `Updated ${configFileName} file`);
return UpdateResult.updated;
} else {
return UpdateResult.cancelled;
}
}

function parseIntegrationName(spec: string) {
const result = parseNpmName(spec);
if (!result) return;
Expand Down Expand Up @@ -755,3 +889,29 @@ async function askToContinue({ flags }: { flags: yargs.Arguments }): Promise<boo

return Boolean(response.askToContinue);
}

function getDiffContent(input: string, output: string): string | null {
let changes = [];
for (const change of diffWords(input, output)) {
let lines = change.value.trim().split('\n').slice(0, change.count);
if (lines.length === 0) continue;
if (change.added) {
if (!change.value.trim()) continue;
changes.push(change.value);
}
}
if (changes.length === 0) {
return null;
}

let diffed = output;
for (let newContent of changes) {
const coloredOutput = newContent
.split('\n')
.map((ln) => (ln ? green(ln) : ''))
.join('\n');
diffed = diffed.replace(newContent, coloredOutput);
}

return diffed;
}
26 changes: 26 additions & 0 deletions packages/astro/src/core/add/tsconfigs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// tsconfig-resolver types are outdated, so unfortunately we can't use them here, annoying.
Princesseuh marked this conversation as resolved.
Show resolved Hide resolved
export const tsconfigsPresets = {
vue: {
compilerOptions: {
jsx: 'preserve',
},
},
react: {
compilerOptions: {
jsx: 'react-jsx',
jsxImportSource: 'react',
},
},
preact: {
compilerOptions: {
jsx: 'react-jsx',
jsxImportSource: 'preact',
},
},
'solid-js': {
compilerOptions: {
jsx: 'preserve',
jsxImportSource: 'solid-js',
},
},
};
3 changes: 2 additions & 1 deletion packages/integrations/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@
},
"peerDependencies": {
"react": "^17.0.2 || ^18.0.0",
"react-dom": "^17.0.2 || ^18.0.0"
"react-dom": "^17.0.2 || ^18.0.0",
"@types/react": "^17.0.50 || ^18.0.21"
Comment on lines +50 to +51
Copy link
Member Author

Choose a reason for hiding this comment

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

Unrelated, but those two were missing and are necessary for using React with TypeScript

},
"engines": {
"node": "^14.18.0 || >=16.12.0"
Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.