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

Auston Barboza :

I am trying to build an npm package in typescript. I am not able to require and use the default function exported in the typescript module. I have tried changing module options in tsconfig.json to UMD and AMD, but no luck.

//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.

Kelly Copley :

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 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. 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:

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=32014&siteId=1