【问题标题】:How do you export custom ambient module declarations to be available for use by a consumer?您如何导出自定义环境模块声明以供消费者使用?
【发布时间】:2021-06-03 02:24:00
【问题描述】:

我正在创建一个组件库以供辅助节点应用程序使用(均使用 Typescript)。在这个组件库中,我们有许多环境模块来帮助输入/加载图片文件,例如:

declare module "*.png" {
  const content: string;
  export default content;
}

以及从 3rd 方库中现有但不完整的类型扩展而来的其他类型...例如:

import * as vc from "victory-core";
import * as vl from "victory-label";

declare module "victory-core" {
  export interface CallbackArgs extends vc.CallbackArgs {
    index: number;
  }
}

declare module "victory" {
  export interface VictoryLabelProps extends vl.VictoryLabelProps {
    stringTicks?: string[];
    index?: number;
  }
}

然后使用 Rollup 编译和构建此库,并由辅助应用程序使用。问题是消费者应用程序无法使用这些类型 - 即,如果组件尝试将 stringTicks arg 作为 VictoryLabelProps 的一部分传递,它将不会被识别为有效道具。 与 .png 模块类似,我无法在我的消费者应用程序中加载 png 文件,除非我从字面上复制并粘贴 .d.ts 文件并将其明确添加为我的消费者应用程序的一部分

下面是我的组件库的 tsconfig

{
  "compilerOptions": {
    "declaration": true,
    "declarationDir": "./dist",
    "outDir": "./dist",
    "rootDir": "./src",
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "baseUrl": ".",
    "typeRoots": [
      "src/types",
      "node_modules/@types"
    ],
  },
  "exclude": ["node_modules", "dist"],
  "include": ["src/**/*"],
}

(我尝试基于https://elfi-y.medium.com/typescript-ambient-module-8816c9e5d426添加typeRoots和baseUrl)

还有我的 rollup.config

{
  input: "src/index.ts",
  output: [
    {
      dir: "dist",
      format: "cjs",
      sourcemap: true,
    },
  ],
  external: ["fs"],
  plugins: [
    peerDepsExternal(),
    commonjs({
      include: "node_modules/**",
    }),
    resolve(),
    babel({
      exclude: "node_modules/**",
      babelHelpers: "bundled",
      extensions: [...DEFAULT_EXTENSIONS, ".ts", ".tsx"],
      presets: [["@babel/preset-react", { runtime: "automatic" }]],
    }),
    typescript(),
    json(),
    image(),
    url({
      include: ["**/*.woff", "**/*.woff2"],
      limit: Infinity,
    }),
  ],
};

感谢任何帮助!

【问题讨论】:

    标签: node.js typescript module


    【解决方案1】:

    您需要在库的package.json 中包含types 字段。该字段应包含.d.ts 目录或文件的路径。

    {
      "name": "awesome",
      "author": "Vandelay Industries",
      "version": "1.0.0",
      "main": "./lib/main.js",
      "types": "./lib/main.d.ts"
    }
    

    更多信息:Including declarations in your package

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 2015-10-17
      • 1970-01-01
      • 2016-08-30
      • 2015-08-13
      • 2012-10-12
      • 2012-11-08
      • 2016-09-06
      • 2012-10-12
      相关资源
      最近更新 更多