为什么使用ts写了一个包并发布,但是在项目中引用的时候“找不到类型声明”?

我使用ts写了一个工具,并且将它发布至npm,但是我在其他项目中使用的时候提示“找不到模块“x6tool”或其相应的类型声明。ts(2307)”
下面是我这个工具的package文件及文件目录

这个包已经发布成功,并且在其他项目中安装成功,并且正常使用
image.png
image.png

阅读 2.3k
2 个回答

写对应的类型*.d.ts文件了嘛。你去你安装的node包里面看看。是不是少个类型文件。
帮你问了一下GPT
image.png

相同的代码,vite 中可以 cra(基于 webpack)的不行。

import { useEffect } from 'react'
import X6Tool from 'x6tool'
import './App.css'

function App() {
  useEffect(() => {
    new X6Tool(document.querySelector('#map'))
  }, [])

  return (
    <div>
      <h1>Test</h1>
      <div id="map"></div>
    </div>
  )
}

export default App

cra 编译报错:

Module not found: Error: Can't resolve './X6Tool/index' in 'E:\Projects\x6tool-test1\node_modules\x6tool\dist'
Did you mean 'index.js'?
BREAKING CHANGE: The request './X6Tool/index' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
ERROR in ./node_modules/x6tool/dist/index.js 1:0-36
Module not found: Error: Can't resolve './X6Tool/index' in 'E:\Projects\x6tool-test1\node_modules\x6tool\dist'
Did you mean 'index.js'?
BREAKING CHANGE: The request './X6Tool/index' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.

webpack compiled with 1 error

大概意思是你的 package.json 里有 type: 'module',然后你 index.js 里引用是 /index 没有加 .js 或是 .mjs 后缀报的错。你没给你项目中报的错,我猜测可能和这个一样。

我看你 package.json 里只给了 ESM 格式的产物,而且用的 main 字段。我建议你给两种格式产物,main 字段对应 cjs 格式产物,module 字段对应 ESM 格式产物。

推荐问题
logo
Microsoft
子站问答
访问
宣传栏