简体   繁体   English

无法从 nodejs 中的 typescript 文件中要求默认导出函数

[英]not able to require default exported function from typescript file in nodejs

I am trying to build an npm package in typescript.我正在尝试在打字稿中构建一个 npm 包。 I am not able to require and use the default function exported in the typescript module.我无法要求和使用在 typescript 模块中导出的默认函数。 I have tried changing module options in tsconfig.json to UMD and AMD , but no luck.我曾尝试将tsconfig.json模块选项tsconfig.jsonUMDAMD ,但没有运气。

//index.ts
export default function () {
  console.log("greet");
}

export function greet2() {
  console.log("greet2");
}
//tsconfig.json
{

  "compilerOptions": {
    "target": "es5",
    "module": "commonJS",
    "declaration": true,
    "outDir": "./lib",
    "strict": true
  }
}
//index.js
const greet = require("./lib/index");

greet();

greet.greet2();
//console
greet();
^

TypeError: greet is not a function

Webpack can be used for the solution, But I would like to know if there is any way I can do without using Webpack. Webpack 可用于解决方案,但我想知道是否有任何方法可以不使用 Webpack。

The problem is that you're mixing module syntax.问题是您正在混合模块语法。 When you use require, you are going to get back an object with a default property, and a greet2 property.当您使用 require 时,您将返回一个具有default属性和greet2属性的对象。

require assumes you know how your exports are structured, because they can be in just about any shape you specified with module.exports = anything ES Modules on the other hand have a strict specification. require假设您知道导出的结构,因为它们几乎可以是您指定的任何形状module.exports = anything ES 模块另一方面有严格的规范。 This allows the an import to assume the shape of what comes from an export and do things like conveniently destructuring it for you.这允许导入假设来自导出的形状,并为您方便地解构它。

Currently if you log it, the greet variable will be an object like so:目前,如果你记录它,greet 变量将是一个像这样的对象:

Object {default: function _default(), greet2: function greet2()}

This of course is not a function and thus the error.这当然不是函数,因此不是错误。

If instead you use import syntax如果您使用导入语法

import greet from './lib/index';

it will compile to something equivalent to:它将编译为等效于:

const greet = require('./lib/index').default;

You are of course able to use require yourself in this same fashion, you just have to be aware of the shape of whatever is returned from require and destructure it accordingly.您当然可以以同样的方式使用 require 自己,您只需要了解从require返回的任何内容的形状并相应地对其进行解构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM