Raffaele Iavazzo
Raffaele Iavazzo

Reputation: 21

Default import index.js file

Hi, i have the following ES6 statement in a .js file(within vue.js project that uses webpack):

import my_value from 'path_to_folder1/folder2';  //after `from` keyword, I don't include index.js.

The above statement will be run in this first two steps:

step 1) webpack transpiles ES6 import syntax to require syntax,

for example:

import my_value from 'path_to_folder1/folder2';

will be transpiled to:

var my_value = require('path_to_folder1/folder2'); 

step 2) node.js will search and load (by default) an index.js file from folder2 folder.

step 3) is a node.js feature to default search and load index.js file, from a folder, in a require statement? is there any official documentation on this?

Can you tell me if first two steps are correct?

Then, I would like an answer for the step 3.

It's important. Thanks

Upvotes: 1

Views: 3679

Answers (1)

Kamil Janowski
Kamil Janowski

Reputation: 2025

Node.js will first check if the require's parameter is a directory or a file. If:

  • it's a directory -> load index.js

  • if it's a file:

    • if the specified file exists -> load the file
    • if the specified file does not exist, add the extension .js to it and try to load. Often this is the approach you actually want to go with. Since you might have some TS files and then they are compiled to js... the compiler will figure this thing for you

Now, no, this is NOT necessarily how your import will be compiled. It depends on the configuration of your compiler. By default however, you're looking for the default export of the module. So by default if your import looks like this:

import my_value from 'path_to_folder1/folder2';

then it is actually interpreted as

const {default: my_value} = require('path_to_folder1/folder2');

now, if your path_to_folder1/folder2/index.js specifies export default blabla you're all set. If it doesn't, depending on the configuration of your transpiler you may end up with an error. If your transpiler allows default imports and your module does not have any default export, it will import an object containing all exports.

Upvotes: 1

Related Questions