gpt4 book ai didi

node.js - 具有多个入口点的 Package.json

转载 作者:行者123 更新时间:2023-12-03 12:14:00 24 4
gpt4 key购买 nike

我有一个如下使用的库

import { Foo } from '@me/core';
const foo = new Foo();
package.json那个图书馆的样子
"name": "@me/core",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"license": "MIT",
...
dist/index.js它的入口点。然而,现在我将只为 NodeJs 项目提供一个导入,而为 Web 项目提供一个。理想情况下,我会为 NodeJs 提供类似的东西
import { Foo } from '@me/core/nodejs';
如果你正在做一个网络项目,你可以做
import { Foo } from '@me/core/web';
我的理解是 @me/core/nodejs@me/core/web这种方式将是不同的 NPM 包,这不是我想要的。我希望它在 1 个 npm 包中。
我试图改变图书馆的 index.ts 文件,从
export * from './foo';
进入
import * as nodejs from './nodejs';
import * as web from './web';

export { web, nodejs };
这实际上有效,但我现在必须使用它(在 NODEJS 项目中),如下所示
import { nodejs } from '@me/core';

const foo = new nodejs.Foo();
有没有办法导入这个我不需要 nodejs每次?
正如你所看到的,我不太确定我应该在这里做什么,所以任何帮助都将不胜感激!
更新:根据@Klaycon 的建议,我看到以下错误:
enter image description here

最佳答案

当您使用 ECMAScript 模块时,请参阅 package entry points 上的 node.js 文档:

In a package’s package.json file, two fields can define entry points for a package: "main" and "exports". The "main" field is supported in all versions of Node.js, but its capabilities are limited: it only defines the main entry point of the package.
The "exports" field provides an alternative to "main" where the package main entry point can be defined while also encapsulating the package, preventing any other entry points besides those defined in "exports". This encapsulation allows module authors to define a public interface for their package.


因此,在您的 package.json 中,您可以定义 exports像这样:
  "main": "dist/index.js",
"exports": {
".": "dist/index.js",
"./nodejs": "dist/nodejs",
"./web": "dist/web",
}

关于node.js - 具有多个入口点的 Package.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63058081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com