Skip to content

fix(tsconfig): parse extended tsconfigs when transpiling script blocks #502

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 2 commits into from
Nov 3, 2022
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
34 changes: 34 additions & 0 deletions e2e/2.x/basic/components/ExtendedTsConfig.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<template>
<div>
{{ exclamationMarks }}
<type-script-child />
</div>
</template>

<script lang="ts">
import TypeScriptChild from './TypeScriptChild.vue'

import moduleRequiringEsModuleInterop from './ModuleRequiringEsModuleInterop'

// The default import above relies on esModuleInterop being set to true in order to use it from
// an import statement instead of require. This option is configured in the tsconfig.base.json,
// so if we are no longer fully processing the tsconfig options (extended from a base config)
// this test should fail. This was one of the only reliable ways I could get a test to fail if
// these conditions are not being met and happen to be the use-case which was triggering errors
// in my config setup.
Comment on lines +17 to +18
Copy link
Contributor Author

Choose a reason for hiding this comment

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

In my project, we were setting esModuleInterop in a shared base config, and Vue.extend(...) was throwing a TypeError when running the test because it "could not read property 'extend' from undefined".


if (moduleRequiringEsModuleInterop()) {
throw new Error('Should never hit this')
}

export default {
computed: {
exclamationMarks(): string {
return 'string'
}
},
components: {
TypeScriptChild
}
}
</script>
1 change: 1 addition & 0 deletions e2e/2.x/basic/components/ModuleRequiringEsModuleInterop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = () => false
7 changes: 7 additions & 0 deletions e2e/2.x/basic/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import Jsx from './components/Jsx.vue'
import Constructor from './components/Constructor.vue'
import { compileStyle } from '@vue/component-compiler-utils'
import ScriptSetup from './components/ScriptSetup'
import ExtendedTsConfig from './components/ExtendedTsConfig.vue'

jest.mock('@vue/component-compiler-utils', () => ({
...jest.requireActual('@vue/component-compiler-utils'),
compileStyle: jest.fn(() => ({ errors: [], code: '' }))
Expand Down Expand Up @@ -163,6 +165,11 @@ test('processes SFC with <script setup>', () => {
expect(wrapper.html()).toContain('Welcome to Your Vue.js App')
})

test('handles extended tsconfig.json files', () => {
const wrapper = mount(ExtendedTsConfig)
expect(wrapper.element.tagName).toBe('DIV')
})

test('should pass properly "styleOptions" into "preprocessOptions"', () => {
const filePath = resolve(__dirname, './components/Basic.vue')
const fileString = readFileSync(filePath, { encoding: 'utf8' })
Expand Down
21 changes: 21 additions & 0 deletions e2e/2.x/basic/tsconfig.base.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "es6"],
"module": "es2015",
"moduleResolution": "node",
"types": ["vue-typescript-import-dts", "node"],
"isolatedModules": false,
"experimentalDecorators": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"suppressImplicitAnyIndexErrors": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"esModuleInterop": true,
"allowJs": true
}
}
19 changes: 1 addition & 18 deletions e2e/2.x/basic/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,3 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "es6"],
"module": "es2015",
"moduleResolution": "node",
"types": ["vue-typescript-import-dts", "node"],
"isolatedModules": false,
"experimentalDecorators": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"suppressImplicitAnyIndexErrors": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"allowJs": true
}
"extends": "./tsconfig.base.json"
}
34 changes: 34 additions & 0 deletions e2e/3.x/basic/components/ExtendedTsConfig.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<template>
<div>
{{ exclamationMarks }}
<type-script-child />
</div>
</template>

<script lang="ts">
import TypeScriptChild from './TypeScriptChild.vue'

import moduleRequiringEsModuleInterop from './ModuleRequiringEsModuleInterop'

// The default import above relies on esModuleInterop being set to true in order to use it from
// an import statement instead of require. This option is configured in the tsconfig.base.json,
// so if we are no longer fully processing the tsconfig options (extended from a base config)
// this test should fail. This was one of the only reliable ways I could get a test to fail if
// these conditions are not being met and happen to be the use-case which was triggering errors
// in my config setup.

if (moduleRequiringEsModuleInterop()) {
throw new Error('Should never hit this')
}

export default {
computed: {
exclamationMarks(): string {
return 'string'
}
},
components: {
TypeScriptChild
}
}
</script>
1 change: 1 addition & 0 deletions e2e/3.x/basic/components/ModuleRequiringEsModuleInterop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = () => false
7 changes: 7 additions & 0 deletions e2e/3.x/basic/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import ScriptSetup from './components/ScriptSetup.vue'
import ScriptSetupSugarRef from './components/ScriptSetupSugarRef.vue'
import FunctionalRenderFn from './components/FunctionalRenderFn.vue'
import CompilerDirective from './components/CompilerDirective.vue'
import ExtendedTsConfig from './components/ExtendedTsConfig.vue'

// TODO: JSX for Vue 3? TSX?
import Jsx from './components/Jsx.vue'
Expand Down Expand Up @@ -207,3 +208,9 @@ test('ensure compilerOptions is passed down', () => {
const elm = document.querySelector('h1')
expect(elm.hasAttribute('data-test')).toBe(false)
})

test('handles extended tsconfig.json files', () => {
mount(ExtendedTsConfig)
const elm = document.querySelector('div')
expect(elm).toBeDefined()
})
21 changes: 21 additions & 0 deletions e2e/3.x/basic/tsconfig.base.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "es6"],
"module": "es2015",
"moduleResolution": "node",
"types": ["vue-typescript-import-dts", "node"],
"isolatedModules": false,
"experimentalDecorators": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"suppressImplicitAnyIndexErrors": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"esModuleInterop": true,
"allowJs": true
}
}
19 changes: 1 addition & 18 deletions e2e/3.x/basic/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,3 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "es6"],
"module": "es2015",
"moduleResolution": "node",
"types": ["vue-typescript-import-dts", "node"],
"isolatedModules": false,
"experimentalDecorators": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"suppressImplicitAnyIndexErrors": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"allowJs": true
}
"extends": "./tsconfig.base.json"
}
2 changes: 1 addition & 1 deletion packages/vue2-jest/lib/ensure-require.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const throwError = require('./utils').throwError
const throwError = require('./throw-error')

module.exports = function(name, deps) {
let i, len
Expand Down
3 changes: 3 additions & 0 deletions packages/vue2-jest/lib/throw-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = function throwError(msg) {
throw new Error('\n[vue-jest] Error: ' + msg + '\n')
}
52 changes: 41 additions & 11 deletions packages/vue2-jest/lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const ensureRequire = require('./ensure-require')
const throwError = require('./throw-error')
const constants = require('./constants')
const loadPartialConfig = require('@babel/core').loadPartialConfig
const { loadSync: loadTsConfigSync } = require('tsconfig')
const { resolveSync: resolveTsConfigSync } = require('tsconfig')
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
Expand Down Expand Up @@ -68,23 +70,55 @@ const getBabelOptions = function loadBabelOptions(filename, options = {}) {
return loadPartialConfig(opts).options
}

const tsConfigCache = new Map()

/**
* Load TypeScript config from tsconfig.json.
* @param {string | undefined} path tsconfig.json file path (default: root)
* @returns {import('typescript').TranspileOptions | null} TypeScript compilerOptions or null
*/
const getTypeScriptConfig = function getTypeScriptConfig(path) {
const tsconfig = loadTsConfigSync(process.cwd(), path || '')
if (!tsconfig.path) {
if (tsConfigCache.has(path)) {
return tsConfigCache.get(path)
}

ensureRequire('typescript', ['typescript'])
const typescript = require('typescript')

const tsconfigPath = resolveTsConfigSync(process.cwd(), path || '')
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Note: we are still using the tsconfig package to resolve the path to the tsconfig file in the same way that tsconfig.loadSync was previously doing.

if (!tsconfigPath) {
warn(`Not found tsconfig.json.`)
return null
}
const compilerOptions =
(tsconfig.config && tsconfig.config.compilerOptions) || {}

return {
compilerOptions: { ...compilerOptions, module: 'commonjs' }
const parsedConfig = typescript.getParsedCommandLineOfConfigFile(
tsconfigPath,
{},
{
...typescript.sys,
onUnRecoverableConfigFileDiagnostic: e => {
const errorMessage = typescript.formatDiagnostic(e, {
getCurrentDirectory: () => process.cwd(),
getNewLine: () => `\n`,
getCanonicalFileName: file => file.replace(/\\/g, '/')
})
warn(errorMessage)
}
Comment on lines +99 to +106
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This will provide us with an error message if typescript is unable to read the tsconfig file or one of the extended files because they don't exist or don't parse etc.

Copy link
Member

Choose a reason for hiding this comment

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

This is nice, I like good error messages.

}
)

const compilerOptions = parsedConfig ? parsedConfig.options : {}

const transpileConfig = {
compilerOptions: {
...compilerOptions,
module: typescript.ModuleKind.CommonJS
Comment on lines +112 to +115
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Note: As in the old code, we override the module with commonjs. I changed this to use the enum instead of a string literal because it failed to compile in my typescript version of this code. The expected value of CompilerOptions['module'] is ModuleKind, but it does seem to accept the string literals at runtime.

}
}

tsConfigCache.set(path, transpileConfig)

return transpileConfig
}

function isValidTransformer(transformer) {
Expand Down Expand Up @@ -131,10 +165,6 @@ const getCustomTransformer = function getCustomTransformer(
: transformer
}

const throwError = function error(msg) {
throw new Error('\n[vue-jest] Error: ' + msg + '\n')
}

const stripInlineSourceMap = function(str) {
return str.slice(0, str.indexOf('//# sourceMappingURL'))
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vue3-jest/lib/ensure-require.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const throwError = require('./utils').throwError
const throwError = require('./throw-error')
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Note: In order to use ensure-require from within utils.js, I needed to break the circular dependency. This was done by moving throw-error out of utils and into its own module so that ensure-require doesn't depend on utils.


module.exports = function(name, deps) {
let i, len
Expand Down
3 changes: 3 additions & 0 deletions packages/vue3-jest/lib/throw-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = function throwError(msg) {
throw new Error('\n[vue-jest] Error: ' + msg + '\n')
}
55 changes: 43 additions & 12 deletions packages/vue3-jest/lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const ensureRequire = require('./ensure-require')
const throwError = require('./throw-error')
const constants = require('./constants')
const loadPartialConfig = require('@babel/core').loadPartialConfig
const { loadSync: loadTsConfigSync } = require('tsconfig')
const { resolveSync: resolveTsConfigSync } = require('tsconfig')
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
Expand Down Expand Up @@ -68,24 +70,57 @@ const getBabelOptions = function loadBabelOptions(filename, options = {}) {
return loadPartialConfig(opts).options
}

const tsConfigCache = new Map()

/**
* Load TypeScript config from tsconfig.json.
* @param {string | undefined} path tsconfig.json file path (default: root)
* @returns {import('typescript').TranspileOptions | null} TypeScript compilerOptions or null
*/
const getTypeScriptConfig = function getTypeScriptConfig(path) {
const tsconfig = loadTsConfigSync(process.cwd(), path || '')
if (!tsconfig.path) {
if (tsConfigCache.has(path)) {
return tsConfigCache.get(path)
}

ensureRequire('typescript', ['typescript'])
const typescript = require('typescript')

const tsconfigPath = resolveTsConfigSync(process.cwd(), path || '')
if (!tsconfigPath) {
warn(`Not found tsconfig.json.`)
return null
}
const compilerOptions =
(tsconfig.config && tsconfig.config.compilerOptions) || {}

// Force es5 to prevent const vue_1 = require('vue') from conflicting
return {
compilerOptions: { ...compilerOptions, target: 'es5', module: 'commonjs' }
const parsedConfig = typescript.getParsedCommandLineOfConfigFile(
tsconfigPath,
{},
{
...typescript.sys,
onUnRecoverableConfigFileDiagnostic: e => {
const errorMessage = typescript.formatDiagnostic(e, {
getCurrentDirectory: () => process.cwd(),
getNewLine: () => `\n`,
getCanonicalFileName: file => file.replace(/\\/g, '/')
})
warn(errorMessage)
}
}
)

const compilerOptions = parsedConfig ? parsedConfig.options : {}

const transpileConfig = {
compilerOptions: {
...compilerOptions,
// Force es5 to prevent const vue_1 = require('vue') from conflicting
target: typescript.ScriptTarget.ES5,
module: typescript.ModuleKind.CommonJS
}
}

tsConfigCache.set(path, transpileConfig)

return transpileConfig
}

function isValidTransformer(transformer) {
Expand Down Expand Up @@ -133,10 +168,6 @@ const getCustomTransformer = function getCustomTransformer(
: transformer
}

const throwError = function error(msg) {
throw new Error('\n[vue-jest] Error: ' + msg + '\n')
}

const stripInlineSourceMap = function(str) {
return str.slice(0, str.indexOf('//# sourceMappingURL'))
}
Expand Down