gpt4 book ai didi

node.js - 如何配置使用从 PureScript 编译的 JavaScript 模块的 TypeScript 项目?

转载 作者:搜寻专家 更新时间:2023-10-30 20:42:54 26 4
gpt4 key购买 nike

TL;DR 我想为已编译的 PureScript 模块创建 TypeScript 类型,并将它们分发到我的 npm 包中。我非常乐意手动维护这些类型,我只是不知道我需要在 tsconfig.json(上游和下游)和 package.json 中放入什么。


我有一个 project其中核心功能是使用 TypeScript CLI 在 PureScript 中实现的,所有这些最终都通过 npm 作为 JavaScript 分发。我创建了一个 similar project布局更简单:

.
├── cli # TypeScript CLI project
│   ├── main.ts
│   └── tsconfig.json

├── output # Compiled PureScript modules
│   └── People
│   ├── externs.json
│   └── index.js

├── src # PureScript source
│   └── People.purs

└── types # TypeScript types for PureScript modules
└── People.d.ts

src/People.purs 中,我定义了核心功能:

module People where

type Person = { name :: String }

david :: Person
david = { name: "David "}

types/People.d.ts 中,我为 PureScript 模块定义了 TypeScript 类型,因此我可以安全地从 TypeScript 使用它们:

declare module "People" {
export interface Person {
name: string;
}

export const david: Person;
}

最后,在 cli/main.ts 中,我想导入具有我定义的 TypeScript 类型的已编译 PureScript 模块:

import * as People from "People";

console.log(People.david);

我可以构建它,但是当我尝试运行最终的 JavaScript (node cli/main.js) 时, 生成的 require 调用tsc 失败是因为它们不使用绝对路径——在这种情况下,require("People") 应该是 require("./People")。在 TypeScript 中制作 import 语句会取消类型关联。

我很难实现这些目标:

  • 维护从 TypeScript 导入的所有 PureScript 模块的 TypeScript 类型。
  • 确保 TypeScript 进行类型检查。
  • 确保 require 对 PureScript 模块的调用在运行时解析。
  • 使用 npm 包分发 TypeScript 类型,以便 TypeScript 使用者也可以使用这些类型。

如果您有从 TypeScript 中获取 PureScript 模块并通过 npm 分发所有这些模块的经验,我将不胜感激一些指导!

最佳答案

您的 Purescript 模块名为“Person”,但应该是“People”。我认为通过相对路径导入你可能会部分到达那里,但我不认为 d.ts 文件中有相对路径类型这样的东西。

我检查了你的项目并重命名了模块,然后我将 allowJs 设置为 true 并内嵌模块:

import * as OutputPeople from "../output/People";

type Person = {
name: string;
};

type PeopleModule = {
david: Person
}

const People: PeopleModule = OutputPeople

console.log(People.david);

我将修改放在此处的分支上:https://github.com/justinwoo/ps-js-ts-interop/commit/fc7c1239f9d1bac1cf2bea35f7a07d30c46a5f64

关于node.js - 如何配置使用从 PureScript 编译的 JavaScript 模块的 TypeScript 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46505582/

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