Skip to content

Commit

Permalink
feat: support a src attribute on a script block
Browse files Browse the repository at this point in the history
  • Loading branch information
ktsn committed Feb 4, 2018
1 parent f0cfc69 commit e35079d
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/lib/ts-file-map.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import assert = require('assert')
import path = require('path')
import ts = require('typescript')
import vueCompiler = require('vue-template-compiler')
import { readFileSync, exists } from './file-util'
Expand Down Expand Up @@ -62,7 +63,7 @@ export class TsFileMap {

let src = readFileSync(rawFileName)
if (src && isVueFile(rawFileName)) {
src = extractCode(src)
src = extractCode(src, fileName)
}

if (src !== file.text) {
Expand Down Expand Up @@ -102,11 +103,22 @@ export class TsFileMap {
* Extract TS code from single file component
* If there are no TS code, return undefined
*/
function extractCode (src: string): string | undefined {
function extractCode (src: string, fileName: string): string | undefined {
const script = vueCompiler.parseComponent(src, { pad: true }).script
if (script == null || script.lang !== 'ts') {
if (script == null) {
return undefined
}

// Load an external TS file if it referred via src attribute.
if (script.src && isSupportedFile(script.src)) {
const srcFileName = path.resolve(path.dirname(fileName), script.src)
return readFileSync(srcFileName)
}

if (script.lang !== 'ts') {
return undefined
}

return script.content
}

Expand Down
6 changes: 6 additions & 0 deletions test/expects/src.vue.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
declare const _default: {
data(): {
foo: string;
};
};
export default _default;
7 changes: 7 additions & 0 deletions test/fixtures/src.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default {
data () {
return {
foo: 'Hello'
}
}
}
11 changes: 11 additions & 0 deletions test/fixtures/src.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<template>
<div>{{ foo }}</div>
</template>

<script lang="ts" src="./src.ts"></script>

<style>
div {
color: red;
}
</style>
6 changes: 6 additions & 0 deletions test/specs/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ describe('generate', () => {
test(fixtures('import.vue.d.ts'), expects('import.vue.d.ts'))
})
})

it('should emit d.ts of ts file referred via src attribute', () => {
return gen(fixtures('src.vue'), compilerOptions).then(() => {
test(fixtures('src.vue.d.ts'), expects('src.vue.d.ts'))
})
})
})

function normalize (str: string): string {
Expand Down

0 comments on commit e35079d

Please sign in to comment.