reactjs 为什么我必须在库导入中包含“/dist

bkhjykvo  于 2022-12-22  发布在  React
关注(0)|答案(1)|浏览(237)

我正在用vite作为构建工具编写一个react组件库。
我已经编译了项目并将其部署到npm注册表中,当我从客户端应用程序导入它时,我必须在导入中包含“/dist”。
从客户端应用程序,导入如下...

import { Tuple } from 'tuple-ui';

...导致vscode中出现以下错误:

Could not find a declaration file for module 'tuple-ui'. '/arbitrary/path/tuple/dist/tuple.umd.js' implicitly has an 'any' type. Try `npm i --save-dev @types/tuple-ui` if it exists or add a new declaration (.d.ts) file containing `declare module 'tuple-ui';`ts(7016)

但是,当我在导入中包含“dist”时...

import { Tuple } from 'tuple-ui/dist';

...错误消失。
下面是我的组件库的vite.config.ts:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import dts from 'vite-plugin-dts';
import * as path from 'path';

export default defineConfig({
  plugins: [
    react(),
    dts({
      insertTypesEntry: true,
    }),
  ],
  build: {
    lib: {
      entry: path.resolve(__dirname, 'src/lib/index.ts'),
      name: 'tuple',
      fileName: 'tuple'
    },
    rollupOptions: {
      external: ['react', 'react-dom'],
      output: {
        globals: {
          react: 'React',
          'react-dom': 'ReactDOM',
        }
      }
    }
  },
})

这里是 Package 。json:

{
  "name": "tuple-ui",
  "version": "0.0.10",
  "license": "MIT",
  "author": "budl",
  "scripts": {
    "dev": "vite",
    "tsc": "tsc",
    "tscv": "tsc --version",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "storybook": "start-storybook -p 6006",
    "build-storybook": "build-storybook",
    "chromatic": "npx chromatic --project-token=e183f70dfe01"
  },
  "dependencies": {
    "chromatic": "^6.9.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0"
  },
  "devDependencies": {
    "@babel/core": "^7.18.6",
    "@storybook/addon-actions": "^6.5.9",
    "@storybook/addon-essentials": "^6.5.9",
    "@storybook/addon-interactions": "^6.5.9",
    "@storybook/addon-links": "^6.5.9",
    "@storybook/builder-vite": "^0.1.38",
    "@storybook/react": "^6.5.9",
    "@storybook/testing-library": "^0.0.13",
    "@types/react": "^18.0.0",
    "@types/react-dom": "^18.0.0",
    "@vitejs/plugin-react": "^1.3.0",
    "babel-loader": "^8.2.5",
    "typescript": "^4.9.4",
    "vite": "^2.9.9",
    "vite-plugin-dts": "^0.9.10"
  },
  "readme": "ERROR: No README data found!",
  "type": "module",
  "files": [ "dist" ],
  "main": "./dist/tuple.umd.js",
  "module": "./dist/tuple.es.js",
  "exports": {
    ".": {
      "import": "./dist/tuple.es.js",
      "require": "./dist/tuple.umd.js"
    }
  }
}
erhoui1w

erhoui1w1#

你得到这个错误是因为你使用typescript开发你的库,并且你的库中没有typescript文件的模块声明,甚至你可以看到这个错误是如何建议你运行这个命令来安装库的类型的:

npm i --save-dev @types/tuple-ui

在这种情况下,您有两种选择:
1-运行建议的命令,看看它是否能解决您的问题。
2-编写库声明文件。(在这里你可以得到更多的文档:https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html
当导入/dist目录时,错误消失了,因为在这个目录中,您已经将 typescript 文件转换为javascript。

相关问题