为什么我需要在我要发布的包的导入语句中指定`src`?

问题描述 投票:0回答:1

我正在学习如何将打字稿包发布到 NPM。这是一个简单的包,仅导出一些随机数函数,但最终它会做更多的事情:

src
  /random
    /index.ts
  /index.ts
package.json
tsconfig.json
.gitignore

当我将 npm 包导入另一个 typescript 项目时,出现以下错误:

import {Random} from "@whiterook6/my-package";

console.log(Random.randomInt(1, 10));
Cannot find module '@whiterook6/my-package' or its corresponding type declarations.ts(2307)

但是如果我将导入更改为此,它就会起作用:

import {Random} from "@whiterook6/my-package/src";

console.log(Random.randomInt(1, 10));

我在库包中做错了什么才得到这个可怕的结果,我该如何更改它以便用户可以编写这些类型的导入?

import {Random, Logger} from "@whiterook6/my-package";

这是我的 tsconfig.json 文件:

{
  "compilerOptions": {
    "target": "ESNext", // Specify the ECMAScript target version
    "module": "ESNext", // Specify the module code generation
    "moduleResolution": "node", // Specify module resolution strategy
    "declaration": true, // Generate declaration files
    "emitDeclarationOnly": true, // Only emit declaration files
    "outDir": "./src", // Redirect output structure to the directory
    "rootDir": "./src", // Specify the root directory of input files
    "strict": true, // Enable strict type checking options
    "esModuleInterop": true, // Enable compatibility with CommonJS and ES modules
    "skipLibCheck": true, // Skip type checking of declaration files
    "forceConsistentCasingInFileNames": true // Ensure consistent casing in imports
  },
  "include": [
    "src/**/*" // Include all files in the src directory
  ],
  "exclude": [
    "node_modules", // Exclude node_modules directory
    "dist" // Exclude dist directory
  ]
}
typescript npm
1个回答
0
投票

您需要在您的

exports
中设置
package.json

这看起来像这样:

package.json

exports: {
    "./random": "./dist/random/index.js"
}

有关更多信息,请参阅此处:https://stackoverflow.com/a/74551879/27893855

© www.soinside.com 2019 - 2024. All rights reserved.