Search code examples
javascriptreactjswebpackisomorphic-javascriptreact-starter-kit

How to configure module.alias properly


I would like to use resolve.alias feature from webpack in my projects using React Starter Kit.

For example:

Instead this:

import Component from '../../components/Component

I would like to use

import Component from 'components/Component

I've added this configuration on config.js file:

resolve: {
  alias: {
    components: './src/components'
  }
}

This resolve.alias enables aliases for projects bundled with webpack but doesn't working with React Starter Kit.


Solution

  • You need to configure alias with the full path:

    resolve: {
      alias: {
        components: path.resolve(__dirname, './src/components')
      }
    }
    

    Instead of using alias, I usually use modules to "mount" my entire src folder:

    resolve: {
      modules: [
        path.resolve(__dirname, "./src"),
        'node_modules',
      ],
    

    which, assuming I have a dir structure like:

    src/
    src/components/...
    src/util/...
    src/routes/...
    src/views/...
    

    let's me write these sorts of imports:

    import C from 'components/C';
    import foo from 'util/foo';
    import routes from 'routes/blah';
    ...