【问题标题】:javascript can not use import in chrome firefox and nodejavascript 无法在 chrome firefox 和 node 中使用导入
【发布时间】:2020-04-01 12:03:29
【问题描述】:

我有这 3 个文件:

index.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

chrome 中的错误:

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

我怎样才能让它在任何地方都能工作?特别是在节点中?

【问题讨论】:

  • 我认为支持 ES6 是个问题。

标签: javascript node.js google-chrome web firefox


【解决方案1】:

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

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

  • 浏览器:这些错误已经足够解释:页面必须在http/s 协议上提供,而不是file。因此,它可以与 liveserver 一起使用,但不能直接访问页面

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 2022-01-01
    • 2012-04-22
    • 2017-04-26
    • 1970-01-01
    相关资源
    最近更新 更多