6

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

  • src
  • style
  • components

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'
user2167582
  • 5,986
  • 13
  • 64
  • 121

2 Answers2

2

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:

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

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.

ZeroCho
  • 1,358
  • 10
  • 23