What's Right Way To Import A Module Javascript Node.js
Solution 1:
There is no difference in the result, both will work. The second is just unnecessarily verbose (which is largely harmless, but I for one wouldn't use ./../myModule.js). The modules documentation says:
A required module prefixed with
'/'is an absolute path to the file. For example,require('/home/marco/foo.js')will load the file at/home/marco/foo.js.A required module prefixed with
'./'is relative to the file callingrequire(). That is,circle.jsmust be in the same directory asfoo.jsforrequire('./circle')to find it.Without a leading
'/','./', or'../'to indicate a file, the module must either be a core module or is loaded from a node_modules folder.
Re your edit:
Also, I see some imports are done using the file extension, and other don't. What's the correct way?
That same documentation addresses this just above the earlier quotes:
If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions:
.js,.json, and finally.node.
.jsfiles are interpreted as JavaScript text files, and.jsonfiles are parsed as JSON text files..nodefiles are interpreted as compiled addon modules loaded with dlopen.

Post a Comment for "What's Right Way To Import A Module Javascript Node.js"