【问题标题】:Using Typescript functions in plain VueJS project在普通的 VueJS 项目中使用 Typescript 函数
【发布时间】: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 并且我确实想使用类型,所以我最好从现在开始移动已经可以移动到打字稿的东西。

【问题讨论】:

标签: javascript typescript vue.js vuejs2


【解决方案1】:

安装 TS 并将 tsconfig.json 配置文件添加到基于 Vue CLI/Webpack 的 Vue 项目是不够的,因为您还需要配置 Webpack 以正确处理 TS 文件或 Vue SFC 中的 <script lang='ts'> 块(使用 ts-loader )

在 Vue CLI 管理的项目中开始使用 TS 的最简单方法是使用 CLI 插件@vue/cli-plugin-typescript

vue add typescript

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 2021-02-11
    • 2021-10-19
    • 2021-04-29
    • 2013-05-09
    相关资源
    最近更新 更多