Importing js modules by directory name

I’m upgrading a React application and have found that I need to modify the import statements to get them to work.

For example, in the old version, the following import works without errors:

import { User } from '../System'

Note that System is a directory on my file system that contains User, a js file that ends with export default User.

In my upgraded version of the app, the System directory still exists, but the above import gives me Can't resolve '../System' in 'C:\my app\.

It turns out that to get the import working properly now, I need to change it to the following:

import User from '../System/User';

If I understand correctly, this relates to js module system changes made with ES6.

My question, though, is regarding the specification of a directory in the import statement (System above). Why would it be that I was previously able to name a file directory in the import statement instead of the actual js script/module itself? Is that approach of using a directory in the import statement still possible? And if so, is it ever advisable?

Update: based on AKX’s comment, I noticed the System directory does indeed contain an index.js, which apparently is what makes the import from the directory itself possible.

>Solution :

When an import points to a directory, and only a file, Webpack (which most React setups use) follows Node’s’s conventions and will attempt to import index.js from that directory if it exists. That’s the only condition under which importing from a path that points to a directory works – your previous build probably had /System/index.js (which would allow importing with from '../System'). If you rename the file you’re importing to anything else – such as to User.js – importing using only the directory path will fail.

And if so, is it ever advisable?

Sure, if you want. It’s a style choice but is commonly done.

Leave a Reply