0

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

3
  • i send an answer read this and say it useful or not :)
    – ama coder
    Commented Feb 13, 2022 at 11:47
  • i dont understand why it error happend.
    – ama coder
    Commented Feb 13, 2022 at 11:48
  • i know the why now :) you should use a JS compiler like babel. read my answer edits.
    – ama coder
    Commented Feb 13, 2022 at 13:44

2 Answers 2

1

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.

0

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>
1
  • this for DOM/web front end js. not for nodeJS
    – ama coder
    Commented Feb 13, 2022 at 11:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.