【发布时间】:2021-09-27 02:47:36
【问题描述】:
TL;DR:如何在我的普通 js Vue-Components 中导入和使用 typescript 模块?
我有一个 Vue 2(还不是 3)项目。在这个项目中,我将一些逻辑移到了 es 模块中,以提高可测试性并使其更具可重用性。像这样的:
export const getHistory = () => {
// ...
}
在一个普通的 JS Vue 组件中,我会 import {getHistory} from '../modules/listHistory' 那个函数并将它与一些表示逻辑结合使用。
现在,我想将此函数移动到这样的打字稿模块:
interface ListHistory {
id: number;
}
export function getHistory(): ListHistory[] {
// ...
}
我(天真地)假设我可以继续导入该函数并以与之前在我的 JS-Components 中相同的方式使用它。但是,这不起作用并失败并显示以下错误消息:
These relative modules were not found:
* ../../modules/listHistory in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/quick-actions/quick-actions.vue?vue&type=script&lang=js&
在the vue guidelines on typescript 之后,我已将tsconfig.json 文件添加到我的项目中:
{
"compilerOptions": {
"target": "es5",
"strict": true,
"module": "es2015",
"moduleResolution": "node"
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
我还添加了typescript 作为我项目的开发依赖项。
在寻找解决方案时,我只能找到尝试在 typescript 项目中导入纯 js 模块的人,这与我想做的事情完全不同。
我知道将 Typescript 的内容导入到纯 JS 代码中并不能为您提供 Typescript 的所有优势,但由于我会在某个时候将整个东西迁移到 VueJS 3 并且我确实想使用类型,所以我最好从现在开始移动已经可以移动到打字稿的东西。
【问题讨论】:
-
你在使用 Vue CLI 吗?
-
@MichalLevý 是的,Vue CLI。
-
这似乎很好用,谢谢!你想写一个“真实”的答案来获得声誉还是我应该这样做?
标签: javascript typescript vue.js vuejs2