打字稿:要求语句不是导入语句的一部分 [英] Typescript : require statement not part of an import statement

查看:32
本文介绍了打字稿:要求语句不是导入语句的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打字稿版本 2.2.2

Typescript version 2.2.2

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

I wrote this require in my UserRoutzr.ts

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

TSLint 发出以下警告:

TSLint is raising the following warning:

require statement not part of an import statement

如果我把它改成:

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

然后它引发了一个错误:

Then it's raising an error :

TS1003 Identifier expected

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

How should I rewrite this require ? thanks for feedback

推荐答案

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

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 会解决它.它会影响到 users 的正确导出类型 (IUser[]).

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");

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

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

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

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");

另见:TypeScript 2.4 发行说明

这篇关于打字稿:要求语句不是导入语句的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆