javascript - 模块 `require` 基本路径

标签 javascript node.js npm

我正在使用 typescript 。我的源代码位于 src 中。转译时,Typescript 将其结果输出到 lib 文件夹。因此,当需要我的包组件时,我必须编写以下内容:

import { myModuleMain } from 'mylib/lib'
import { ComponentA }   from 'mylib/lib/ComponentA'
import { ComponentB }   from 'mylib/lib/ComponentB'

好吧,当这种情况只发生一次时,就没关系。问题是当需要几个或多个这样的组件时。到处都有十几个 /lib 路径段,我试图摆脱它,简单地执行以下操作:

import { myModuleMain } from 'mylib'
import { ComponentA }   from 'mylib/ComponentA'
import { ComponentB }   from 'mylib/ComponentB'

我应该找到一种方法来定义我的库的基本路径。但据我所知,我必须更改 lib 代码中的 require 搜索路径。有没有办法在不改变搜索路径的情况下实现相同的行为?例如,通过 package.json 属性?

我自愿省略在单个 main 入口点中导出所有组件的选项,因为除了我的 main 之外的文件不应该由最终用户使用:只有插件可以使用它们。换句话说,我希望有多个入口点,全部位于lib文件夹中。使用 package.json 中的 main 属性只会简化第一个模块的 import 语句,例如 myModuleMain

最佳答案

我在库配置(package.json)上使用main:

{
    "name": "mylib",
    "description": "My library...",
    "version": "1.0.0",
    "main": "./lib/index.js",
    ......
}

来自documentation :

The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.

This should be a module ID relative to the root of your package folder.

For most modules, it makes the most sense to have a main script and often not much else.

此外,在 ts.config 上我有以下配置:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "./lib",    
    "rootDir": "./src",
    "moduleResolution": "node",
    ....
  }
}

关于javascript - 模块 `require` 基本路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49884746/

相关文章:

javascript - Internet Explorer 中的 jQuery UI 对话框和 maxHeight

javascript - 如何使用 javascript 链接多个任务?

javascript - 如何从 nodejs aws s3 getObject 回调数据中检索元数据?

node.js - 如何使用 node.js 通过 ListMatchingProducts API 访问 Amazon mws 中的 10 多个产品

node.js - 如何全局卸载 npm 包 commitizen?

javascript - 嵌套短路对象的快速方法?

javascript - 将 javascript 对象 camelCase 键转换为 underscore_case

javascript - 从 JS 代码定位 div

javascript - 在 WebSocket 上接收 ArrayBuffer (ws)

javascript - SystemJS 未找到 RxJS 根目录