javascript - 在 Typescript Vue 项目中使用 Javascript 模块

标签 javascript node.js typescript vue.js node-modules

问题

我正在尝试使用 https://github.com/moonwave99/fretboard.js在我的 Vue 项目中。我尝试将模块导入组件中,如下所示:

<template>
  <div>
    <div id="fretboard" />
  </div>
</template>
<script lang="ts">
import { Fretboard } from '@moonwave99/fretboard.js';
const fretboard = new Fretboard({
  el: '#fretboard',
  fretColor: 'blue',
  dotFill: 'red'
});
fretboard.render([
  {
    string: 5,
    fret: 3
  },
  {
    string: 4,
    fret: 2
  },
  {
    string: 2,
    fret: 1
  }
]);
</script>

这会导致以下错误:

Could not find a declaration file for module '@moonwave99/fretboard.js'. '/Users/xxx/guitar-apps/node_modules/@moonwave99/fretboard.js/dist/fretboard.cjs.js' implicitly has an 'any' type.
  Try `npm install @types/moonwave99__fretboard.js` if it exists or add a new declaration (.d.ts) file containing `declare module '@moonwave99/fretboard.js';`Vetur(7016)

我尝试运行npm install @types/moonwave99__fretboard.js命令,但这也导致了一个错误,说'@types/moonwave99__fretboard.js@latest'不在npm 注册表。.

我到处寻找,但找不到适合我的项目的解决方案。有人能解决我的问题吗?

我尝试过的事情

  1. 在项目目录的根目录中创建一个包含声明模块“@moonwave99/fretboard.js”的声明文件
  2. "allowJs": true 添加到我的 tsconfig.ts 文件

其他信息

我的 tsconfig 看起来像:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "allowJs": true,
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

最佳答案

.d.ts文件应位于 include 之一tsconfig.json中配置的路径,并根据tsconfig.json您已发布,即srctests 。这些类型通常存储在 src 中root(您将在 Vue CLI 生成的项目中看到 src/shims.vue.d.ts)。

您可以添加src/fretboard.d.ts文件,包含 declare module '@moonwave99/fretboard.js' 。然后,您必须重新启动 VS Code,以便正确索引键入内容,从而解决错误。

关于javascript - 在 Typescript Vue 项目中使用 Javascript 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64080207/

相关文章:

javascript - 如何通过订阅组件内的变量来存储可观察值 - Angular4

javascript - 无法在电子邮件中显示背景图片

reactjs - 从 apollo-client 中的客户端缓存中删除项目的正确方法

javascript - 在 vue 上关闭模态时如何运行语句?

javascript - 如何纠正分页和侧边栏的对齐方式

javascript - 如何动态配置 Passportjs 策略?

javascript - 如何在运行 karma 时修复 "There is no server listening on port 9876"错误?

node.js - 处理回调函数中引发的错误的正确方法是什么?

javascript - 如何使用 puppeteer 通过占位符选择元素

javascript - 从像字符串一样的 JSON 生成有效的 JSON - 正则表达式?