簡體   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