mercredi 1 avril 2020

javascript can not use import in chrome firefox and node

I have those 3 files:

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!

Error node:

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

Error in 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

Error in 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”.

Where it works: parcel and liveserver(the one in visualcode)

How can I make it so that it works everywhere? especially in node?




Aucun commentaire:

Enregistrer un commentaire