首页 > 解决方案 > javascript 无法在 chrome firefox 和 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

main.js

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

火狐浏览器错误:

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 中的那个)

我怎样才能使它无处不在?特别是在节点?

标签: javascriptnode.jsgoogle-chromewebfirefox

解决方案


模块在节点和浏览器上不起作用的原因有两个:

  • 节点:如果您使用高于 13 的版本(如果我没记错的话),您type必须modulepackage.json. 如果您使用的是以前的版本,则必须使用 --experimental-modules 标志(我建议您阅读文档https://nodejs.org/docs/latest-v12.x/ ​​api/esm.html )。

  • 浏览器:这些错误已经足够解释:页面必须基于http/s协议而不是file. 出于这个原因,它可以与 liveserver 一起使用,但不能直接访问页面


推荐阅读