-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
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
Changes from 1 commit
f48be94
ba72072
2ccd442
6704167
c307e48
0b2b268
146900e
bf9acd1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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` | ||
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'; | ||
|
@@ -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 { | ||
|
@@ -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); | ||
|
@@ -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'); | ||
|
@@ -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: { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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( | ||
|
@@ -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', | ||
|
@@ -533,6 +544,7 @@ interface InstallCommand { | |
flags: string[]; | ||
dependencies: string[]; | ||
} | ||
|
||
async function getInstallIntegrationsCommand({ | ||
integrations, | ||
cwd = process.cwd(), | ||
|
@@ -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; | ||
|
@@ -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; | ||
} |
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', | ||
}, | ||
}, | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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" | ||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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