feat(typescript): add convertJsToTs and allowJs options (#4212)

Close #2676

At the moment when we run `vue add`, Vue CLI renames all `*.js` files to `*.ts`. This PR introduces two new prompts on `@vue/cli-plugin-typescript` late-invokation:

1. `convertJsToTs`: if set to `true`, renames all `.js` files to `.ts`. Otherwise renames only `main.js` -> `main.ts`;
2. `allowJs`: if set to `true`, adds `allowJs: true` to TSConfig compiler options.

(cherry picked from commit 38debb4d14)
This commit is contained in:
Natalia Tepluhina
2019-07-03 05:49:15 +03:00
committed by Haoqun Jiang
parent 1f0d66f539
commit 51e63cf7ae
4 changed files with 42 additions and 14 deletions

View File

@@ -1,22 +1,33 @@
module.exports = (api, { tsLint = false } = {}) => {
// delete all js files that have a ts file of the same name
// and simply rename other js files to ts
module.exports = (api, { tsLint = false, convertAllFiles = true } = {}) => {
const jsRE = /\.js$/
const excludeRE = /^tests\/e2e\/|(\.config|rc)\.js$/
const convertLintFlags = require('../lib/convertLintFlags')
api.postProcessFiles(files => {
for (const file in files) {
if (jsRE.test(file) && !excludeRE.test(file)) {
const tsFile = file.replace(jsRE, '.ts')
if (!files[tsFile]) {
let content = files[file]
if (tsLint) {
content = convertLintFlags(content)
if (convertAllFiles) {
// delete all js files that have a ts file of the same name
// and simply rename other js files to ts
for (const file in files) {
if (jsRE.test(file) && !excludeRE.test(file)) {
const tsFile = file.replace(jsRE, '.ts')
if (!files[tsFile]) {
let content = files[file]
if (tsLint) {
content = convertLintFlags(content)
}
files[tsFile] = content
}
files[tsFile] = content
delete files[file]
}
delete files[file]
}
} else {
// rename only main file to main.ts
const tsFile = api.entryFile.replace(jsRE, '.ts')
let content = files[api.entryFile]
if (tsLint) {
content = convertLintFlags(content)
}
files[tsFile] = content
delete files[api.entryFile]
}
})
}

View File

@@ -1,7 +1,9 @@
module.exports = (api, {
classComponent,
tsLint,
lintOn = []
lintOn = [],
convertJsToTs,
allowJs
}, _, invoking) => {
if (typeof lintOn === 'string') {
lintOn = lintOn.split(',')
@@ -82,5 +84,5 @@ module.exports = (api, {
hasJest: api.hasPlugin('unit-jest')
})
require('./convert')(api, { tsLint })
require('./convert')(api, { tsLint, convertJsToTs })
}

View File

@@ -9,6 +9,9 @@
<%_ if (options.classComponent) { _%>
"experimentalDecorators": true,
<%_ } _%>
<%_ if (options.allowJs) { _%>
"allowJs": true,
<%_ } _%>
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,

View File

@@ -36,6 +36,18 @@ const prompts = module.exports = [
value: 'commit'
}
]
},
{
name: `convertJsToTs`,
type: `confirm`,
message: `Convert all .js files to .ts?`,
default: true
},
{
name: `allowJs`,
type: `confirm`,
message: `Allow .js files to be compiled?`,
default: false
}
]