Unverified Commit 8e3c5c2b authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Improve TypeScript package install experience (#7548)

This change will prompt the user about missing packages using the same DX instead of two separate code paths.
parent 5a014bdf
/// <reference types="next" />
...@@ -6,7 +6,10 @@ ...@@ -6,7 +6,10 @@
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "preserve",
"lib": ["dom", "es2017"], "lib": [
"dom",
"es2017"
],
"module": "esnext", "module": "esnext",
"moduleResolution": "node", "moduleResolution": "node",
"noEmit": true, "noEmit": true,
...@@ -18,6 +21,11 @@ ...@@ -18,6 +21,11 @@
"strict": true, "strict": true,
"target": "esnext" "target": "esnext"
}, },
"exclude": ["node_modules"], "exclude": [
"include": ["**/*.ts", "**/*.tsx"] "node_modules"
],
"include": [
"**/*.ts",
"**/*.tsx"
]
} }
...@@ -9,15 +9,6 @@ import resolve from 'next/dist/compiled/resolve/index.js' ...@@ -9,15 +9,6 @@ import resolve from 'next/dist/compiled/resolve/index.js'
const exists = promisify(fs.exists) const exists = promisify(fs.exists)
const writeFile = promisify(fs.writeFile) const writeFile = promisify(fs.writeFile)
const resolveP = (req: string, opts: any): Promise<string> => {
return new Promise((_resolve, reject) => {
resolve(req, opts, (err, res) => {
if (err) return reject(err)
_resolve(res)
})
})
}
function writeJson(fileName: string, object: object): Promise<void> { function writeJson(fileName: string, object: object): Promise<void> {
return writeFile( return writeFile(
fileName, fileName,
...@@ -35,56 +26,60 @@ async function hasTypeScript(dir: string): Promise<boolean> { ...@@ -35,56 +26,60 @@ async function hasTypeScript(dir: string): Promise<boolean> {
return typescriptFiles.length > 0 return typescriptFiles.length > 0
} }
export async function verifyTypeScriptSetup(dir: string): Promise<void> { async function checkDependencies({
const tsConfigPath = path.join(dir, 'tsconfig.json') dir,
const yarnLockFile = path.join(dir, 'yarn.lock') isYarn,
}: {
const hasTsConfig = await exists(tsConfigPath) dir: string
const isYarn = await exists(yarnLockFile) isYarn: boolean
const hasTypeScriptFiles = await hasTypeScript(dir) }) {
const requiredPackages = [
{ file: 'typescript', pkg: 'typescript' },
{ file: '@types/react/index.d.ts', pkg: '@types/react' },
]
const missingPackages = requiredPackages.filter(p => {
try {
resolve.sync(p.file, { basedir: dir })
} catch (_) {
return true
}
})
if (!(hasTsConfig || hasTypeScriptFiles)) { if (missingPackages.length < 1) {
return return
} }
let firstTimeSetup = !hasTsConfig && hasTypeScriptFiles const packagesHuman = missingPackages
.map(
// Ensure TypeScript is installed (p, index, { length }) =>
let typescriptPath = '' (index > 0
let ts: typeof import('typescript') ? index === length - 1
? length > 2
const toInstall: string[] = [] ? ', and '
try { : ' and '
await resolveP('@types/react/index.d.ts', { basedir: dir }) : ', '
} catch (_) { : '') + p.pkg
toInstall.push('@types/react') )
} .join('')
const packagesCli = missingPackages.map(p => p.pkg).join(' ')
try {
typescriptPath = await resolveP('typescript', { basedir: dir })
ts = require(typescriptPath)
} catch (_) {
toInstall.push('typescript')
const toInstallStr = toInstall.join(' ')
console.error( console.error(
chalk.bold.red( chalk.bold.red(
`It looks like you're trying to use TypeScript but do not have ${chalk.bold( `It looks like you're trying to use TypeScript but do not have the required package(s) installed.`
toInstallStr
)} installed.`
) )
) )
console.error()
console.error( console.error(
chalk.bold( chalk.bold(`Please install ${chalk.bold(packagesHuman)} by running:`)
'Please install',
chalk.cyan.bold(toInstallStr),
'by running',
chalk.cyan.bold(
(isYarn ? 'yarn add --dev' : 'npm install --save-dev') +
' ' +
toInstallStr
) + '.'
) )
console.error()
console.error(
`\t${chalk.bold.cyan(
(isYarn ? 'yarn add --dev' : 'npm install --save-dev') + ' ' + packagesCli
)}`
) )
console.error()
console.error( console.error(
chalk.bold( chalk.bold(
'If you are not trying to use TypeScript, please remove the ' + 'If you are not trying to use TypeScript, please remove the ' +
...@@ -94,9 +89,24 @@ export async function verifyTypeScriptSetup(dir: string): Promise<void> { ...@@ -94,9 +89,24 @@ export async function verifyTypeScriptSetup(dir: string): Promise<void> {
) )
console.error() console.error()
process.exit(1) process.exit(1)
}
export async function verifyTypeScriptSetup(dir: string): Promise<void> {
const tsConfigPath = path.join(dir, 'tsconfig.json')
const yarnLockFile = path.join(dir, 'yarn.lock')
const hasTsConfig = await exists(tsConfigPath)
const isYarn = await exists(yarnLockFile)
const hasTypeScriptFiles = await hasTypeScript(dir)
let firstTimeSetup = !hasTsConfig && hasTypeScriptFiles
if (!(hasTsConfig || hasTypeScriptFiles)) {
return return
} }
await checkDependencies({ dir, isYarn })
const ts = await import('typescript')
const compilerOptions: any = { const compilerOptions: any = {
// These are suggested values and will be set when not present in the // These are suggested values and will be set when not present in the
// tsconfig.json // tsconfig.json
...@@ -278,18 +288,4 @@ export async function verifyTypeScriptSetup(dir: string): Promise<void> { ...@@ -278,18 +288,4 @@ export async function verifyTypeScriptSetup(dir: string): Promise<void> {
`/// <reference types="next" />${os.EOL}` `/// <reference types="next" />${os.EOL}`
) )
} }
if (toInstall.length > 0) {
console.warn(
chalk.red(
`\n${toInstall.join(' ')} ${
toInstall.length === 1 ? 'is' : 'are'
} needed when using TypeScript with Next.js. Please install ${
toInstall.length === 1 ? 'it' : 'them'
} with ${
isYarn ? 'yarn add --dev' : 'npm install --save-dev'
} ${toInstall.join(' ')}\n`
)
)
}
} }
...@@ -46,7 +46,10 @@ const babelServerOpts = { ...@@ -46,7 +46,10 @@ const babelServerOpts = {
} }
] ]
], ],
plugins: [['@babel/plugin-proposal-class-properties', { loose: true }]] plugins: [
'babel-plugin-dynamic-import-node',
['@babel/plugin-proposal-class-properties', { loose: true }]
]
} }
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
...@@ -113,13 +116,9 @@ export async function compile (task) { ...@@ -113,13 +116,9 @@ export async function compile (task) {
} }
export async function bin (task, opts) { export async function bin (task, opts) {
const babelOpts = {
...babelServerOpts,
plugins: [...babelServerOpts.plugins, 'babel-plugin-dynamic-import-node']
}
await task await task
.source(opts.src || 'bin/*') .source(opts.src || 'bin/*')
.babel(babelOpts, { stripExtension: true }) .babel(babelServerOpts, { stripExtension: true })
.target('dist/bin', { mode: '0755' }) .target('dist/bin', { mode: '0755' })
notify('Compiled binaries') notify('Compiled binaries')
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment