javascript - 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 中的那个)
我怎样才能使它无处不在?特别是在节点?
解决方案
模块在节点和浏览器上不起作用的原因有两个:
节点:如果您使用高于 13 的版本(如果我没记错的话),您
type
必须module
在package.json
. 如果您使用的是以前的版本,则必须使用 --experimental-modules 标志(我建议您阅读文档https://nodejs.org/docs/latest-v12.x/ api/esm.html )。浏览器:这些错误已经足够解释:页面必须基于
http/s
协议而不是file
. 出于这个原因,它可以与 liveserver 一起使用,但不能直接访问页面
推荐阅读
- python - 继续收到错误:'urllib.error.HTTPError:HTTP 错误 400:错误请求'
- kubernetes - 优先选择某些节点直到满
- php - 如何在登录该人之前使我的recaptcha需要
- mysql - 在查询中生成具有给定行数的 SQL 查询
- pygame - 在 pygame 中,密钥读取被延迟
- javascript - 在 Chrome Devtools 中监听 CSS 类的变化
- c - 在释放所有变量之前检查是否为空,但仍然出现内存错误
- r - 闪亮 - 如何显示数据框?
- google-apps-script - 工作表和日历之间的 Apps 脚本问题
- reactjs - 具有相似 url 的链接的 activeClassName