webpack

Make absolute paths relative to the project root in 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.


Solution

  • 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.