繁体   English   中英

导入 ECMAScript 6 时出现“Uncaught SyntaxError: Cannot use import statement outside a module”

[英]"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

我正在使用 ArcGIS JSAPI 4.12,并希望使用Spatial Illusions在 map 上绘制军事符号。

当我将milsymbol.js添加到脚本时,控制台返回错误

未捕获的语法错误:无法在模块外使用导入语句`

所以我将type="module"添加到脚本中,然后它返回

未捕获的 ReferenceError:未定义 ms

这是我的代码:

<link rel="stylesheet" href="https://js.arcgis.com/4.12/esri/css/main.css">
<script src="https://js.arcgis.com/4.12/"></script>
<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>

<script>
    require([
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/MapImageLayer",
        "esri/layers/FeatureLayer"
    ], function (Map, MapView, MapImageLayer, FeatureLayer) {

        var symbol = new ms.Symbol("SFG-UCI----D", { size: 30 }).asCanvas(3);
        var map = new Map({
            basemap: "topo-vector"
        });

        var view = new MapView({
            container: "viewDiv",
            map: map,
            center: [121, 23],
            zoom: 7
        });
    });
</script>

因此,无论我是否添加type="module" ,总是会出现错误。 但是,在Spatial Illusions的官方文档中,脚本中并没有任何type="module" 我现在真的很困惑。 他们如何在不添加类型的情况下设法让它工作?

文件milsymbol.js

import { ms } from "./ms.js";

import Symbol from "./ms/symbol.js";
ms.Symbol = Symbol;

export { ms };

我收到此错误是因为我忘记了脚本标签中的type="module"

<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>

更新 Node.js / NPM

"type": "module"添加到package.json文件中。

{
  // ...
  "type": "module",
  // ...
}

注意:当使用模块时,如果你得到ReferenceError: require is not defined ,你需要使用import语法而不是require 你不能在它们之间混合和匹配,所以如果你需要同时使用两者,你需要选择一个或使用捆绑器

看起来错误的原因是:

  1. 您当前正在src目录中加载源文件,而不是dist目录中的构建文件(您可以在此处查看预期的分发文件)。 这意味着您在未更改/未捆绑的 state 中使用本机源代码,导致以下错误: Uncaught SyntaxError: Cannot use import statement outside a module 这应该通过使用捆绑版本来解决,因为 package 正在使用汇总来创建捆绑包。

  2. 您收到Uncaught ReferenceError: ms is not defined错误的原因是因为模块是作用域的,并且由于您使用本机模块加载库,因此ms不在全局 scope 中,因此无法在以下脚本标记中访问.

看起来您应该能够加载此文件的dist版本以在window上定义ms 从库作者那里查看这个例子,看看如何做到这一点的例子。

我通过用“require”替换“import”解决了我的问题。

// import { parse } from 'node-html-parser';
const parse = require('node-html-parser');

在我将 type="module" 添加到脚本之前,我也面临同样的问题。

之前是这样的

<script src="../src/main.js"></script>

并将其更改为

<script type="module" src="../src/main.js"></script>

它工作得很好。

我通过执行以下操作解决了这个问题:

在浏览器中使用 ECMAScript 6 模块时,请在文件中使用 .js 扩展名,并在脚本标签中添加type = "module"

在 Node.js 环境中使用 ECMAScript 6 模块时,在文件中使用扩展名.mjs并使用以下命令运行文件:

node --experimental-modules filename.mjs

编辑:这是在 node12 是最新的 LTS 时编写的,这不适用于 node 14 LTS。

我不知道这在这里是否很明显。 我想指出,就客户端(浏览器)JavaScript 而言,您可以将type="module"添加到外部和内部 js 脚本中。

说,你有一个文件'module.js':

var a = 10;
export {a};

您可以在执行导入的外部脚本中使用它,例如:

<!DOCTYPE html><html><body>
<script type="module" src="test.js"></script><!-- Here use type="module" rather than type="text/javascript" -->
</body></html>

测试.js:

import {a} from "./module.js";
alert(a);

您也可以在内部脚本中使用它,例如:

<!DOCTYPE html><html><body>
<script type="module">
    import {a} from "./module.js";
    alert(a);
</script>
</body></html>

值得一提的是,对于相对路径,不能省略“./”字符,即:

import {a} from "module.js";     // this won't work

有三种方法可以解决这个问题:

1.第一种:在脚本中,include type=module

    <script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>

2.第二个:在node.js中,进入你的package.json文件

    {
        // ...
        "type": "module",
        // ...
    }

3.第三种:将import替换为required

Try this

import { parse } from 'node-html-parser';
parse = require('node-html-parser');

Else try this

//import { parse } from 'node-html-parser';
parse = require('node-html-parser');

对我来说,这是由于没有将库(特别是typeORM ,使用ormconfig.js文件,在entities键下)引用到src文件夹,而不是dist文件夹...

   "entities": [
      "src/db/entity/**/*.ts", // Pay attention to "src" and "ts" (this is wrong)
   ],

代替

   "entities": [
      "dist/db/entity/**/*.js", // Pay attention to "dist" and "js" (this is the correct way)
   ],

我在React中遇到了这个错误,并通过以下步骤修复了它:

  1. Go到工程根目录,打开Package.json文件进行编辑。

  2. 添加"type":"module";

  3. 保存并重新启动服务器。

如果要对模块使用 import 而不是 require(),请在package.json文件中更改或添加moduletype

例子:

package.json文件

{
  "name": "appsample",
  "version": "1.0.0",
  "type": "module",
  "description": "Learning Node",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Chikeluba Anusionwu",
  "license": "ISC"
}
import http from 'http';

var host = '127.0.0.1',
    port = 1992,
    server = http.createServer();

server.on('request', (req, res) => {
  res.writeHead(200, {"Content-Type": "text/plain"});
  res.end("I am using type module in package.json file in this application.");
});

server.listen(port, () => console.log(
    'Listening to server ${port}. Connection has been established.'));

将“类型”:“模块”添加到package.json文件中。

并重新启动您的应用程序:

npm start

然后你的问题就解决了。

我在香草 JavaScript 上编码。 如果您也这样做,只需将 type="module" 添加到您的脚本标签。

也就是之前的代码:

<script src="./index.js"></script>

更新代码:

<script type="module" src="./index.js"></script>`

为什么会发生这种情况以及更多可能的原因:

很多接口仍然不理解ES6 JavaScript 语法/特性。 因此,无论何时在任何文件或项目中使用 ES6,都需要将其编译为ES5

SyntaxError: Cannot use import statement outside a module错误的可能原因是您尝试独立运行文件。 您尚未安装和设置 ES6 编译器,例如Babel ,或者您的 runscript 中的文件路径错误/不是编译文件。

如果您想在没有编译器的情况下继续,最好的解决方案是使用 ES5 语法,在您的情况下是var ms = require(./ms.js); . 这可以稍后根据需要进行更新,或者更好地设置您的编译器,并确保您的文件/项目在运行之前进行编译,并确保您的运行脚本正在运行通常命名为 dist、build 或任何您命名它的编译文件以及指向你的runscript中编译的文件是正确的。

对我来说,这有帮助:

  1. 在我使用的.ts文件中: import prompts from "prompts";
  2. 并在文件tsconfig.json中使用了"module": "commonjs"

触发错误是因为您在 HTML 文件中链接到的文件是该文件的未捆绑版本。 要获得完整的捆绑版本,您必须使用npm安装它:

npm install --save milsymbol

这会将完整的 package 下载到您的node_modules文件夹。

然后,您可以在node_modules/milsymbol/dist/milsymbol.js访问独立的缩小 JavaScript 文件

您可以在任何目录中执行此操作,然后只需将以下文件复制到您的/src目录。

使用此代码。 它对我很有效:

将此脚本标签添加到文件index.html

<script type="module">
    import { ms } from "./ms.js";
    import Symbol from "./ms/symbol.js";
</script>

就我而言,我更新了

"lib": [
      "es2020",
      "dom"
    ]

"lib": [
  "es2016",
  "dom"
]

在我的tsconfig.json文件中。

我在尝试使用 import Express.js时遇到了这个错误。

而不是import express from 'express';

我用const express = require('express');

EXPO 遇到了同样的错误。

主要解决方案是在package.json文件中添加"type": "module",

我的文件,你可以找到两个 package.json

代码图像

但是,您必须检查哪个是正确的 package.json。

在我的情况下,有两个 package.json 文件,那么您应该将其添加到服务器文件中。

要确定哪个是正确的 package.json,请找到"scripts": { "test": "echo \"Error: no test specified\" && exit 1" },

在↑这一行下面,添加"type": "module",

我必须将一些数据从外部文件(js 文件)导入到我的 html 文件中的 script.js 中。

数据.js

const data = {a: 1, b: 2}

通过添加type=module我得到了cors错误。

我发现只需将data.js包含在我的 html 文件中,我就可以将data.js导入我的script.js中。

例如,以前我的 html 文件包括

<script src="assets/script.js"></script>

由于我需要data.js中的一些数据,我只是将我的 html 文件更改为

<script src="assets/data.js"></script>
<script src="assets/script.js"></script>

即在script.js之前包含data.js ,从而可以访问我在script.js中的数据变量

我刚刚在我的 Package.json 文件中添加了“type”:“module”,它对我有用。

我想我会添加这个注释,因为它对我来说不是很明显。 您需要将type="module"添加到所有脚本包含中,而不仅仅是要用于实用程序文件的脚本。

索引.html:

<script type="module" src="js/controllers/utils.js"></script>
<script type="module" src="js/controllers/main.js"></script>`

主.js:

import myFunction from './utils.js

utils.js:

export default myFunction

我在使用 cygwin 的 windows 上的节点遇到了类似的问题。 事实证明,虽然错误消息说SyntaxError: Cannot use import statement outside a module ,但我的问题与长路径有关。

为了解决这个问题,我不得不

  1. 在该位置创建一个临时驱动器subst I: YourProjectdir
  2. 导航到该替换驱动器cd I:
  3. 再次运行 node 命令node Yourfile.js

TypeScript,反应,索引。html

    //conf.js:
    window.bar = "bar";
    
   //index.html 
    <script type="module" src="./conf.js"></script>
    
    //tsconfig.json
    "include": ["typings-custom/**/*.ts"]
    
    //typings-custom/typings.d.ts
    declare var bar:string;

    //App.tsx
    console.log('bar', window.bar);
    or
    console.log('bar', bar);

那是因为你还没有导出。 .ts 文件需要导出 class 格式,而在 a.js 文件中,我们将使用exports function。

因此,我们必须使用var_name = require("<pathfile>")来使用这些文件函数。

好吧,就我而言,我不想更新我的package.json文件并将文件类型更改为 mjs。

所以我环顾四周,发现更改文件tsconfig.json中的模块会影响结果。 我的ts.config文件是:

{
  "compilerOptions": {
    "target": "es2020",
    "module": "es2020",
    "lib": [
      "es2020",
    ],
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "baseUrl": "."
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "./src/**/*.ts"
  ]
}

像这样将模块从"module": "es2020"更改为"module": "commonjs"解决了我的问题。

我正在使用MikroORM并认为它可能不支持CommonJS之上的任何模块。

提供的答案都不适合我,但我找到了一个不同的解决方案: 如何在 Node.js 中启用 ECMAScript 6 导入

安装 ESM:

npm install --save esm

使用 ESM 运行:

node -r esm server.js

对我来说是一个编译问题。 我已经添加


  "devDependencies": {
    ...
    "@babel/cli": "^7.7.5",
    "@babel/core": "^7.7.5",
    "@babel/node": "^7.7.4",
    "@babel/plugin-proposal-class-properties": "^7.7.4",
    "@babel/plugin-transform-instanceof": "^7.8.3",
    "@babel/plugin-transform-runtime": "^7.7.6",
    "@babel/preset-env": "^7.7.5",
    "@babel/register": "^7.7.4",
    "@babel/runtime": "^7.9.6"
  },


  "dependencies": {
    ...
    "@babel/plugin-transform-classes": "^7.15.4"
  },

添加了.babelrc 文件

{
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-instanceof",
    "@babel/plugin-transform-classes"
  ],
  "presets": ["@babel/preset-env"],
  "env": {
    "test": {
      "plugins": ["@babel/plugin-transform-runtime"]
    }
  }
}

使用这个<script type="module" src="/src/moduleA.js"></script>

而不是这个<script>System.import("/src/moduleA.js")</script>

如果你想从模块中导入函数。 比方说, main.js定义了func1func2 ,你想将它们导入 function 到一个新模块, test.js

下面将解决问题。

主.js:

const func1 = () => {console.log('do sth in func1')};
const func2 = () => {console.log('do sth in func2')};

//at the end of module
//export specific functions here
module.exports = { func1, func2 };

测试.js:

// import them here
const{ func1, func2} = require('./survey.js');
func1();
func2();

在节点 JS 中,当我们使用 import 语句而不是 require 时,它会给出这种类型的错误 ex。 使用 const express = require('express');

而不是从“快递”进口快递;

只需在src<script>标记中的名称和扩展名之间添加.pack

IE:

<script src="name.pack.js">
    // Code here
</script>

Babel transpile 失败时会发生此错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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