【问题标题】:SyntaxError: Cannot use import statement outside a module Typescript ErrorSyntaxError:无法在模块 Typescript 错误之外使用 import 语句
【发布时间】:2021-07-08 04:01:00
【问题描述】:

我有多个 .ts 文件,并且在导入某些模块/脚本时遇到了一些打字稿错误。

考虑以下示例:


Sample1.ts
--------

const axios = require('axios');

function sample1() {
...
...

}

Sample2.ts
--------

const axios = require('axios');

function sample2() {
...
...

}


这两个 .ts 文件位于一个文件夹中。我在文件 sample2.ts 中收到错误提示

Cannot redeclare block-scoped variable 'axios'.ts(2451)

为了解决这个错误,我将这一行 const axios = require('axios'); 更改为 import axios from 'axios'; 以导入语句。但是对于导入语句,我收到错误SyntaxError: Cannot use import statement outside a module

我在 tsconfig 文件中的模块和目标分别是 esnext 和 es6。

请有人帮我解决这个问题。我试图消除这些错误很长时间了。

【问题讨论】:

  • 也许在你的 package.json 中添加 type: module 会启用导入语法

标签: javascript typescript importerror tsconfig react-typescript


【解决方案1】:

在package.json 文件中,添加值为“module”的顶级“type”字段。

// package.json
{
  "type": "module"
}

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 2022-01-25
    • 2021-08-24
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 2020-08-25
    • 2020-10-10
    相关资源
    最近更新 更多