I want to import my file functions.js in my file index.js and use variables and functions are in functions.js.
For ex: I have an variable x in my file functions.js. I import functions.js like "import './functions.js';" in my index.js. The path is correct for sure(they are in the same directory). But when i try to use x, i have this next error -> "index.js:01 Uncaught ReferenceError: x is not defined"
functions.js
export var x = 0;
index.js
import './functions.js';
console.log(x);
Thanks ! :)
CodePudding user response:
The point of modules is to get away from this business of sharing everything in a single scope (the global scope, by default in non-module scripts). If you want to do that, don't use modules, use non-module scripts.
Modules are defined in terms of
- What they provide (
export
) - What they expect (
import
)
In general, you're best off making those relationships explicit:
import { x } from "./fonctions.js";
// ...use `x`...
That assumes x
is a named export:
export const x = /*...*/;
// or
export function x() {
// ...
};
// etc.
The closest thing to an "import everything from X" construct in JavaScript modules is a module namespace object import, which looks like this:
import * as fonctions from "./fonctions.js";
You'd then use fonctions.x
to refer to x
. But, x
still has to be exported from fonctions.js
(as above). Anything declared in a module that isn't explicitly exported is private to that module, and so it doesn't show up on the module namespace object.