Skip to content
← Back to Community
Multiple .js files in one project
Profile icon
GopeshMedayil

How to use multiple js files in a single project? It is executing only index.js file every time. Any option to run other than index.js?

Answered by JustARatherRidi [earned 5 cycles]
View Answer
Voters
Profile icon
Somil680
Profile icon
JimLynch
Profile icon
GopeshMedayil
Comments
hotnewtop
Profile icon
JustARatherRidi

Let's say you have two files, index.js and utils.js in the same repl.

If you write this into utils.js and save it,

module.exports = { power: 9001, square: x => x*x };

Then in index.js, you can write the following:

const utils = require('./utils.js'); console.log(utils.power); // 9001 gets printed console.log(utils.square(5)); // 25 gets printed

You can also do the same thing like so

const {power, square} = require('./utils.js'); console.log(power); // 9001 gets printed console.log(square(5)); // 25 gets printed

This way you can split your project across several files, which helps in keeping your code organized.


So you can run code from other files in your index.js this way, but no, you can't really start executing your code from anywhere other than index.js. This makes sense because if your project started executing different files each time, then it wouldn't really be a single 'project' anymore.

You can have a group of related projects though, and if that's what you want, it's probably a good idea to split it into separate repls. Then, you can put all repls within the same folder, so you can choose which one you want to run.


If you're looking to make something in specific, let me know what it is and i might be able to tell you what's the best route you can take.

Hope this helped!

Profile icon
GopeshMedayil

@JustARatherRidi
Thanks a lot. This makes sense

Profile icon
JustARatherRidi

@GopeshMedayil
No problem! If it helped, could you please mark this as the answer?

Profile icon
LucasBrant

@JustARatherRidi
is there no way to implement ES6 "import" functionality?

Profile icon
AlexMogoryan

I use in index.js file

// to run code in file fileName.js require('./fileName');

That helps me to test code just clicking run and make new files.js without making new repls ;D