简体   繁体   中英

Importing Node.js SDK into Typescript running in Node server gave error “ReferenceError: require is not defined”

I'm working on a Node.js SDK for server side usage, and running into this issue " ReferenceError: require is not defined " when trying to import it into my express app using Typescript. Initially I didn't have.d.ts files generated so I imported Typescript and generated the declaration files, but still got the error. My index.js in the SDK package:

const myDep = require('./myDep');
const client = function (sdkKey) {
    const c = {};
    c.do = (user) => {};
    return c;
}

module.exports = client;

The generated index.d.ts file looks like this:

export = client;
declare function client(sdkKey: any): {
    do(user: any): void;
};

This is the tsconfig.json in my SDK package:

{
  "include": ["src/**/*", "src/index.d.ts"],
  "compilerOptions": {
    "resolveJsonModule": true,
    "target": "es6",
    "lib": ["es6"],
    "module": "commonjs",
    "allowJs": true,
    "checkJs": true,
    "declaration": true,
    "emitDeclarationOnly": true,
    "moduleResolution": "Node",
    "outDir": "./dist"
  }
}

I'm using npm link to import it in my node server running typescript, and using import in my app.ts file with

import * as mySDK from 'my-node-js-sdk';

Figured it out in the end and it was fixed by adding a index.d.ts file for type declaration. Also found a couple places in my project where I was using ES6 exports instead of module so had to fix those as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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