繁体   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