Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make absolute paths relative to the project root in Webpack

Tags:

webpack

I find that I need to type ../ a lot to require() files. My directory structure includes these:

js/   components/     ...   actions/     ... 

From the components folder, I need to do import foo from '../actions/fooAction'. Is it possible to make the root directory the root of the project? I.e. I want to do import foo from '/actions/fooAction' instead. I tried setting Webpack's resolve.root option, but it didn't seem to do anything.

like image 769
Leo Jiang Avatar asked Feb 08 '16 01:02

Leo Jiang


People also ask

Can an absolute path be a relative path?

In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.

What is the absolute path to the root directory?

An absolute path is defined as the specifying the location of a file or directory from the root directory(/). In other words we can say absolute path is a complete path from start of actual filesystem from / directory.


1 Answers

The resolve.root option does not modifiy how file modules are resolved.

A required module prefixed with '/' is an absolute path to the file. For example, require('/home/marco/foo.js') will load the file at /home/marco/foo.js.

The / resolves to the root of your file system.

Maybe what you want is to resolve your js folder as a modules directory.

webpack.config.js

resolve: {   root: path.resolve('./js') } 

With this configuration added to your config file will tell webpack to resolve any import or require relative to your js folder. Then, instead of using

import foo from '../actions/fooAction' 

you will be able to:

import foo from 'actions/fooAction` 

Mind the lack of / at the beginning.

like image 99
dreyescat Avatar answered Sep 28 '22 12:09

dreyescat