【问题标题】:Preserve directory structure of a package for importing保留用于导入的包的目录结构
【发布时间】:2020-02-10 16:04:22
【问题描述】:

我正在尝试创建一个目录结构如下的包:

src/
    folder1/
        index.ts
        ...
    folder2/
        index.ts
        ...
    folder3/
        index.ts
        ...
.
.
.

我想将其导入为import { Class1 } from '@package/folder1'import { Class2 } from '@package/folder2' 等。

此时,我可以像import { Class1 } from '@package/lib/folder1' 一样导入我的类。是否有可能实现我的预期行为?

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./lib",
    "rootDir": "./src",
    "rootDirs": ["./src/folder1"],
    "lib": [
      "es2017",
      "esnext.asynciterable"
    ],
    "typeRoots": [
      "./node_modules/@types"
    ],
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "pretty": true,
    "noEmit": false,
    "esModuleInterop": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "lib"]
}

【问题讨论】:

  • 这是您要查找的内容:npmjs.com/package/module-alias?
  • 不完全是。它确实很有用,但我的问题只是lib 目录。我希望我的包的根是lib。所以我不需要在导入中指定它。

标签: node.js typescript import


【解决方案1】:

在我使用的 Typescript 版本(3.7.4)中,这个功能似乎不是开箱即用的。 module-alias 包可能是一种解决方法,但看起来 Typescript 3.8 将允许向导出添加别名。

【讨论】:

    猜你喜欢
    • 2011-09-07
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2011-08-07
    相关资源
    最近更新 更多