簡體   English   中英

javascript 無法在 chrome firefox 和 node 中使用導入

[英]javascript can not use import in chrome firefox and node

我有這 3 個文件:

索引.html

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

sayHi.js

function sayHi(user) {
    alert(`Hello, ${user}!`);
}
export {sayHi}; // a list of exported variables

主文件

import {sayHi} from './say.js';
sayHi('John'); // Hello, John!

錯誤節點:

PS C:\Users\Roxanji\VScode\test4> node .\main.js
C:\Users\Roxanji\VScode\test4\main.js:2
import {sayHi} from './say.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1072:16)
    at Module._compile (internal/modules/cjs/loader.js:1122:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47

鉻錯誤:

Access to script at 'file:///C:/Users/Roxanji/VScode/test4/main.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
index.html:1 GET file:///C:/Users/Roxanji/VScode/test4/main.js net::ERR_FAILED

Firefox 中的錯誤:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/Roxanji/VScode/test4/main.js. (Reason: CORS request not http).
2
Module source URI is not allowed in this document: “file:///C:/Users/Roxanji/VScode/test4/main.js”.

工作地點:parcel 和 liveserver(visualcode 中的那個)

我怎樣才能讓它在任何地方都能工作? 特別是在節點?

模塊在 node 和瀏覽器上不起作用的原因有兩個:

  • 節點:如果您使用的版本高於 13(如果我沒記錯的話),您必須在package.json type valorized to module的字段type 如果您使用的是以前的版本,則必須使用 --experimental-modules 標志(我建議您閱讀文檔https://nodejs.org/docs/latest-v12.x/​​api/esm.html )。

  • 瀏覽器:錯誤已經足夠解釋了:頁面必須在http/s協議上提供,而不是file 出於這個原因,它可以與 liveserver 一起使用,但不能直接訪問頁面

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM