Home > Enterprise >  Using variables and functions in other fileis Node js
Using variables and functions in other fileis Node js

Time:02-14

I have two separate files and I want to use functions and variables in my first file in another file. What I mean is, here is the content of my first file:

const db = mongoose.connection;

and in my second file I need to for example log it:

console.log(db)

I used export and import but it did not work:

export const db = mongoose.connection;

import db from (./db.js)
console.log(db)

I got this error: SyntaxError: Cannot use import statement outside a module

CodePudding user response:

in node js (or modern another js platforms) you can use modules.

in node js. you have 2 choice.

1: common js (CJS) modules:

in a way, nodeJS based on CJS. and CJS‌ modules builtin available in node.

you can imort a CJS‌ module with this code :

const module = required("module file widout .js");

and for create modules (in your module file) :

module.export = {your code};

2 ES6 modules :

es6 is a newer version of JS and that supports modules defaultly.

use module :

your example :)‌ (in question post) :

from module import a;
console.log(a); //1    

create module :

export a = 1

very important for ES6 modules: you should be use a js compiler, like babel to compile es6-21 to es5 nodeJS and browsers (i dont know other platforms) does not support es6 or above JS versions.

CodePudding user response:

Did you create the HTML file, too? If so try loading the second file in as a module type to fix the error.

Put this in your HTML file:

<script type="module" src="secondScript.js"></script>
  • Related