Why import in js not working?

Hello ) Who can tell me why I can not log the variable from another js file?

//index.js file

let sayHi = "Hi";

export default { sayHi };

//data.js file
import { sayHi } from "./index";

console.log(sayHi);

I had this problem a while back and fixed it with updating Node. I was a few updates behind. You can check you current version with cmd prompt node -v (should be 12 or 13)

Thanks ) but this is also in sandbox too https://codesandbox.io/s/upbeat-nash-fvjmv

on computer same , node version - 12.13.0

You run index.js from index.html,
but index.js doesn’t log.

index.js only sets a variable and exports,
but doesn’t do anything else.

data.js has the console.log, so you should find out how to run it.

1 Like

This. I switched: index.html <script src="src/index.js"> to <script src="src/data.js"> and removed default in index.js … export { sayHi }

1 Like

Awesome, great work!

Hopefully OP get’s same results. I still need to practice more about the imports/exports. Only 90% sure why export default { sayHi } doesn’t work. But no idea why export { sayHi as default } wouldn’t :thinking:

Look at the following two cases:

Case 1 - default export:

let sayHi = "Hi";
export default sayHi;

Case 1 - import:

console.log(require("./index")):
// {default: "Hi"}

Case 2 - named export:

let sayHi = "Hi";
export { sayHi };

Case 2 - import:

console.log(require("./index"));
// {sayHi: "Hi"}

The difference:
The default export automatically creates an object property with the key default.
The named export creates an object property with the key you give it.

To import it with an import statement, the syntax without the {} automatically searches for the object property with the key default, e.g. in Case 1.
For Case 2, you have to import it with { sayHi }.

Now it’s your turn to log out what export default { sayHi }; actually exports.
When you see the solution and think about it, it’s actually really simple.

1 Like
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    

    11212


    <script src="./index.js"></script>
</body>
</html>
//index.js file
import {obj} from './data.js'

console.log('000111010');

console.log(obj)
//data.js file

let obj = {a:4,f:44,d:[1,2,3,4,]}

export default obj

Error in console:

 Uncaught SyntaxError: Cannot use import statement outside a module    index.js:1 

Tell me please is wrong with code ?

ya i have a same this problem.
Uncaught SyntaxError: Cannot use import statement outside a module index.js:1

As specified in the error message, the script isn’t a module, and import/export only work if the script is a module.

<script src="./index.js" type="module"></script>