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 :) Commented Feb 13, 2022 at 11:47
  • i dont understand why it error happend. Commented Feb 13, 2022 at 11:48
  • i know the why now :) you should use a JS compiler like babel. read my answer edits. 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.

Sign up to request clarification or add additional context in comments.

Comments

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 Comment

this for DOM/web front end js. not for nodeJS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.