【问题标题】:Using Javascript module in Typescript Vue project在 Typescript Vue 项目中使用 Javascript 模块
【发布时间】:2021-01-12 17:44:24
【问题描述】:

问题

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

<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' is not in the npm registry.。

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

我尝试过的事情

  1. 在我的项目目录的根目录中创建一个包含declare module '@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"
  ]
}

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 感谢tony19,就像一个魅力!现在我的下一个挑战是让这个组件正常工作:)
    猜你喜欢
    • 2022-10-16
    • 1970-01-01
    • 2018-05-28
    • 2021-09-04
    • 2019-04-28
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多