How ES6 resolves import paths and we can customize its behavior

How can we configure the root directory as /

it looks like this behavior depends entirely on the relative path to the current file.

For example, I would rather use a couple of directory paths

  • CAC
  • style
  • Components

and in a deeply nested directory components/header/navbar.js

, I want to import without leading slashes something like:

import Blah from 'src/models/Blah'

      

but instead I have to do

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

      

+3


source to share


2 answers


If you are using webpack to compile ES2015 codes you can use allow field in webpack.config.js file to choose default path

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

      



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

0


source


The module identifier is completely opaque to ECMAScript. That is, there are no rules in the language about how it should be interpreted. The module ID is interpreted by the module loader (and more broadly, the environment) or the module you are using.

eg. Node rules for interpreting module IDs can be found here , and these are the rules that most vendors who work with support for Node.

But many bundles provide ways to customize this.

Summary. How to do this and whether it can be done depends on the loader / module loader / module component you are using. It has nothing to do with the language itself.




Similar questions:

0


source







All Articles