Search code examples
node.jstypescriptmodulerequire

I can only require a module using .require() - is there an alternative?


I have made this npm package: https://github.com/subgeniuscorp/secret-helper

I export an object from the main index.ts file like so:

export default {
  generateSalt,
  createHash,
  generateApiKey,
  validateHash,
  generateRandomString,
}

Here's what my tsconfig.json looks like:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "declaration": true,
    "declarationMap": true,
    "outDir": "./lib",
    "strict": true,
    "moduleResolution": "Node",
    "esModuleInterop": true
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules",
    "test"
  ]
}

Now when I try to use this package in my node project (i.e. not a typescript project), I can only do this like so:

const sh = require("@subgeniuscorp/secret-helper").default;

Is there something I'm doing wrong? Is there anything I can do to require this project without the .default bit? I'm trying to understand if I'm doing something wrong, or if this is how these two modules interact.


Solution

  • What you are looking for is named export

    export {
     generateSalt,
      createHash,
      generateApiKey,
      validateHash,
      generateRandomString,
    }
    

    then you can import it like this using require

    const sh = require("@subgeniuscorp/secret-helper")
    

    with import

    import * as sh from "@subgeniuscorp/secret-helper"
    

    or import using allowSyntheticDefaultImports flag

    import sh from "@subgeniuscorp/secret-helper"