Importing files without naming with Nodejs

Asked

Viewed 102 times

3

I am creating a file structure in an application where each directory contains an "index" file. This index file takes the name of my directory to improve readability. Ex:

foo
|--foo.js    // <- index
|--bin.html
|--bar
|  |--bar.js // <- index
   |--bin.html

With this, the structure that will be used for a require() when importing any file will always be something like

const foo = require('./foo/foo');
const bar = require('./foo/bar/bar');

I look for some way to create a file without the nomenclature, and that Nodejs understands for the import, would be something like:

foo
|--.js // <- sem nome = arquivo da pasta
|--bin.html

So I could work with files similar to namespace’s...

Is there any way to do this with Nodejs?

  • In the case of |--.js // <- sem nome = arquivo da pasta how do you want to do the require?

1 answer

1


You can use foo/index.js and require('./foo') (this is more prudent and common good). Or you can add a package.json in the directory foo and give any name to the main.

eg.

foo/package.json

{"main": "qualquer-coisa.js"}

main.js

require('./foo') // vai dar require em './foo/qualquer-coisa.js'

The complete algorithm is in: https://nodejs.org/api/modules.html#modules_folders_as_modules

But doesn’t do that, does not go much with the conventions.

Better just do

foo
|--index.js
|--bin.html

require('./foo')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.