typescript 打字稿:要求语句不是导入语句的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43112619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:39:49  来源:igfitidea点击:

Typescript : require statement not part of an import statement

typescripttslint

提问by Paleo

Typescript version 2.2.2

打字稿版本 2.2.2

I wrote this require in my UserRoutzr.ts

我在 UserRoutzr.ts 中写了这个要求

const users = <IUser[]> require(path.join(process.cwd() + "/data"));

TSLint is raising the following warning:

TSLint 发出以下警告:

require statement not part of an import statement

if I changed it to :

如果我将其更改为:

import users = <IUser[]> require(path.join(process.cwd() + "/data"));

Then it's raising an error :

然后它引发了一个错误:

TS1003 Identifier expected

How should I rewrite this require ? thanks for feedback

我应该如何重写这个 require ?感谢反馈

回答by Paleo

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.

TypeScript 模块是 ES6 模块的实现。ES6 模块是静态的。您的问题来自动态路径:path.join(process.cwd() + "/data"). 编译器在编译时无法确定它是哪个模块,并且 linter 不喜欢导致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.

您应该使用模块的静态路径。在编译时,TypeScript 会解决它。并且它会影响正确的导出类型 ( IUser[]) 到users.

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

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

注意:如果您的模块data只包含数据,您可以考虑将其更改为 JSON 文件,该文件可以加载 (Node.js) 或捆绑 (Webpack)。

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

更新(从 2019 年 5 月开始)——也可以使用动态导入,TypeScript 接受静态和动态路径:

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

See also: TypeScript 2.4 Release Notes

另请参阅:TypeScript 2.4 发行说明

回答by holi-java

may be you need dynamic module loading, and the code like this:

可能你需要动态模块加载,代码如下:

import {IUser} from './lib/user';
const users:IUser[] = require(path.join(process.cwd() + "/data"));