Multiple .js files in one project
GopeshMedayil (1)

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?

You are viewing a single comment. View All
JustARatherRidi (190)

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!

GopeshMedayil (1)

@JustARatherRidi Thanks a lot. This makes sense

JustARatherRidi (190)

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

LucasBrant (0)

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