繁体   English   中英

如何使用 Vue.js 将 TypeScript 文件编译为 JavaScript

[英]How to compile TypeScript files to JavaScript using Vue.js

我正在尝试使用tsconfig.json文件将TypeScript文件编译成JavaScript文件。 tsconfig.json文件是:

{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "./build",
    "strict": true,
    "esModuleInterop": true
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.test.ts"
  ]
}

上述配置工作正常,并在构建文件夹中创建编译的JavaScript文件。 如果我在build文件夹中使用node run index.js ,它也可以正常工作。 但是如果我将build文件夹中的index.js文件导入到vue组件中,它就不起作用并抛出以下错误:

Uncaught ReferenceError: exports is not defined

我试图通过添加来修复:

"allowSyntheticDefaultImports": true

但没有运气。 我还尝试了官方文档中推荐的配置:

{
  "compilerOptions": {
    "target": "es5",
    "strict": true,
    "module": "es2015",
    "moduleResolution": "node",
    "outDir": "./test-app/src/assets/js"
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.test.ts"
  ]
}

它引发以下错误:

TypeError: fs.existsSync is not a function

我已经在ts文件中需要fs了。

目标是使用已编译的JavaScript文件到Vue.js应用程序中。 任何人都可以帮助我解决tsconfig.json文件中缺少的内容吗? 或者还有其他方法可以使用vue.jsts编译成js吗? 非常感谢。

简短回答:将目标和模块更改为“esnext”

{
  "compilerOptions": {
    "target": "esnext",
    "strict": true,
    "module": "esnext",
    "moduleResolution": "node",
    "outDir": "./test-app/src/assets/js"
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.test.ts"
  ]
}

但是,我不建议在 your.vue 组件中导入构建文件,因为您需要不断构建它们以更新它们。 Here is a page from the vue.js doc on how to integrate typescript: https://v2.vuejs.org/v2/guide/typescript.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM