user2167582
user2167582

Reputation: 6378

how does ES6 resolve import paths and can we customize its behavior

How can we customize a root directory to be the /, seems like this behavior is entirely depending on the relative path of the current file.

For example, I would prefer to use a couple of directory paths

and in deep nested direcotry components/header/navbar.js, i want to import without initialy slashes something like:

import Blah from 'src/models/Blah'

but instead I have to do

import Blah from '../../src/models/Blah'

Upvotes: 6

Views: 4600

Answers (2)

Felix Kling
Felix Kling

Reputation: 816870

The module identifier is completely opaque to ECMAScript. I.e. there are no rules in the language about how it should be interpreted. The module identifier is interpreted by the module loader (and in the broader context, the environment) or the module bundler you are using.

E.g. Node's rules for interpreting module identifiers can be found here and these are the rules that most bundlers that work with Node modules support.

But many bundlers provide ways to customize this.

Summary: How to do this and whether it is possible to do this depends on the environment/module loader/module bundler you are using. It has nothing to do with the language itself.


Related questions:

Upvotes: 2

ZeroCho
ZeroCho

Reputation: 1360

If you use webpack to compile ES2015 codes, you can use resolve field in webpack.config.js to select default path

resolve: {
  modules: [path.join(__dirname, '..', 'app'), 'node_modules'],
},

such like above. In above case, webpack will handle /app directory as root.

Upvotes: 1

Related Questions