导入ECMAScript 6时“未捕获的语法错误:无法在模块外使用导入语句”

我正在使用ArcGIS JSAPI 4.12,并希望使用空间幻觉在地图上绘制军事符号。

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

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

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

未捕获的引用错误: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",总是有错误的。然而,在空间幻觉的官方文档中,脚本中没有任何type="module"。我现在真的很困惑。他们是如何在不添加类型的情况下让它工作的?

文件milsymbol.js

import { ms } from "./ms.js";
import Symbol from "./ms/symbol.js";ms.Symbol = Symbol;
export { ms };
2667599 次浏览

看起来错误的原因是:

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

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

看起来您应该能够加载此文件的dist版本以在window上定义ms。从库作者中查看这个例子以查看如何完成此操作的示例。

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

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

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

npm install --save milsymbol

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

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

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

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

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

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

node --experimental-modules filename.mjs

编辑:这是在节点12是最新的LTS时编写的,这不适用于节点14 LTS。

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

即:

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

我也面临着同样的问题,直到我将type=“模块”添加到脚本中。

在它变成这样之前

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

在把它改成

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

它工作得很好。

我通过将“导入”替换为“需要”来解决我的问题。

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

我不知道这是否在这里显得很明显。我想指出,就客户端(浏览器)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>

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

对我来说,这是由于没有引用库(特别是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)],

更新Node.js/NPM

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

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

说明:使用模块时,如果你得到ReferenceError: require is not defined,你需要使用#1语法而不是require。你不能在它们之间原生混合和匹配,所以你需要选择一个或使用捆绑器如果你需要使用两者

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

  1. 转到项目根目录,打开Package.json文件进行编辑。

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

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

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

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

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

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

在我的情况下,我更新了

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

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

在我的tsconfig.json文件中。

这是因为您没有导出。. ts文件需要导出类格式,而在. js文件中,我们将使用exports函数。

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

我正在使用vanilla JavaScript编码。如果你也在做同样的事情,只需在你的脚本标签中添加一个type=“模块”。

即以前的代码:

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

更新代码:

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

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

而不是import express from 'express';

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

对我来说,这有助于:

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

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

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

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

好吧,在我的情况下,我不想更新我的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,并认为它可能不支持通用文档以上的任何模块。

将“type”:“模块”添加到您的package.json文件中。

然后重新启动您的应用程序:

npm start

那么你的问题就解决了。

如果您想对模块使用导入而不是需要(),请在package.json文件中将type的值更改或添加到module

示例:

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

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

安装ESM:

npm install --save esm

使用ESM运行:

node -r esm server.js

我在世博会上遇到了同样的错误。

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

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

代码图像

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

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

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

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

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

1.第一个:在脚本中,包含type=module

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

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

    {       
"type": "module",       
}

3.第三种:将进口改为所需

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

此错误发生在巴别塔转译失败时。

我只是在我的Package.json文件中添加了“type”:“模块”,它对我有用。

我不得不从外部文件(JavaScript文件)导入一些数据,到我的超文本标记语言文件中的script.js文件。

文件data.js

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

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

我发现我可以通过在我的超文本标记语言文件中包含文件data.js将文件data.js导入到我的script.js文件中。

例如,以前我的超文本标记语言文件包括

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

由于我需要文件data.js中的一些数据,我只是将我的超文本标记语言文件更改为:

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

即,在文件script.js之前包含文件data.js,允许访问文件script.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>

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

index.html:

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

main.js:

import myFunction from './utils.js

utils.js:

export default myFunction

如果您想从模块导入函数。假设,main.js定义了func1func2,您想将它们导入到新模块中,例如test.js

下面将解决这个问题。

main.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 heremodule.exports = { func1, func2 };

test.js:

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