【问题标题】:Node module importing functions with type declarations具有类型声明的节点模块导入函数
【发布时间】:2020-12-24 05:24:09
【问题描述】:

我正在尝试创建一个用于 Expo 项目的 monorepo。为简单起见,我只包括我认为您需要了解我的工作的信息。

文件结构

├── monorepo
│   ├── package.json
│   ├── apps
│   │   ├── myapp
│   │   │   └── App.tsx
│   ├── packages
│   │   │── mylib
│   │   │   │── package.json
│   │   │   │── index.ts
│   │   │   │── index.d.ts
│   │   │   │── test.js

myapp/App.tsx

import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { testing } from "mylib"; << This does not import the function

export default function App() {
  return (
    <View style={styles.container}>
      <Text>{testing}</Text>
      <StatusBar style="auto" />
    </View>
  );
}

mylib/package.json

{
  "name": "mylib",
  "main": "index.ts",
  "types": "index.d.ts",
  ...
}

mylib/index.ts

export default "hello from mylib";

mylib/index.d.ts

export * from "./test";

mylib/test.js

export function testing() {
  return "hello";
}

在 App.tsx 中,如果我在没有大括号的情况下执行 import testing from "mylib",它将把 testing 视为 mylib/index.ts 的默认导出并在屏幕上打印“hello from mylib”。 接下来,我想实际导入测试函数,所以我做了import { testing } from "mylib",但是不识别testing函数。

如何正确地从包中导入函数?我错过了什么?

更新

我相信我遇到的问题与我实际上是从 index.ts 导入的事实有关,无论我的声明文件如何。由于index.ts 只有一个值的默认导出,它不知道我想从那里导入什么。我需要弄清楚声明文件如何与实际的 javascript 功能代码一起使用。

例如,如果我将index.ts 更改为export * from "./test"; 并将App.tsx 编辑为:

import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { testing } from "mylib";

export default function App() {
  return (
    <View style={styles.container}>
      <Text>{testing()}</Text>
      <StatusBar style="auto" />
    </View>
  );
}

然后它将按预期工作

【问题讨论】:

    标签: node.js expo node-modules


    【解决方案1】:

    如果它是node_modules 目录中的已安装包,则只能从包名称导入。在您的情况下,您必须像这样从相对文件路径导入:

    import { testing } from "../../packages/mylib/test";
    

    【讨论】:

    • 这是不正确的。节点模块解析将向上搜索根路径。但这在这种情况下并不重要,因为正如我所写,我使用 monorepo 并使用 yarn 安装我的包。另外,如前所述,我访问该模块没有问题。我在访问特定功能时遇到问题。这是关于导出/导入它的正确方法。
    【解决方案2】:

    我想分享一个great article about node modules and types

    它帮助我了解我没有得到什么。本质上,我将类型声明文件视为应该导出函数的入口点文件。就我而言,我的函数已经有了类型定义,因此甚至不需要向模块添加类型声明文件。

    【讨论】:

      猜你喜欢
      • 2017-09-30
      • 2016-05-01
      • 2016-10-06
      • 2019-07-20
      • 2021-05-23
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      相关资源
      最近更新 更多