Typescript : require statement not part of an import statement

后端 未结 4 2409
我寻月下人不归
我寻月下人不归 2021-02-18 13:10

Typescript version 2.2.2

I wrote this require in my UserRoutzr.ts

const users =  require(path.join(process.cwd() + \"/data\"));

4条回答
  •  离开以前
    2021-02-18 13:39

    TypeScript modules are an implementation of ES6 modules. ES6 modules are static. Your issue comes from the dynamic path: path.join(process.cwd() + "/data"). The compiler can't determine which module it is at compile time, and the linter doesn't like the causes that lead to any.

    You should use a static path to the module. At compile time, TypeScript resolves it. And it affects the right exported type (IUser[]) to users.

    import users = require("./yourModuleThatExportsUsers");
    

    Notice: If your module data contains just data, you could consider to change it to a JSON file, which could be loaded (Node.js) or bundled (Webpack).

    UPDATE (from May 2019) — It is also possible to use dynamic import, with which TypeScript accepts static and dynamic paths:

    const users = await import("./yourModuleThatExportsUsers");
    

    See also: TypeScript 2.4 Release Notes

提交回复
热议问题