1

I have the following import:

// cwd: /project/pages/blog/category/red/index.js

import PageHeader from '../../../components/PageHeader';

And I want to be able to write it this way (anywhere in my project):

// cwd: /project/pages/blog/category/red/index.js

import PageHeader from 'components/PageHeader';

I've tried using webpack resolve option but I can't seem to make it work:

config.resolve = {
  alias: {
    components: [
      path.resolve('../components/')
    ]
  }
};

and

config.resolve = {
  root: [
    path.resolve('../')
  ]
};

Am I missing something ?

My app architecture is forked from React Static Boilerplate, so my webpack.config.js looks like this one

Pierre
  • 18,643
  • 4
  • 41
  • 62

3 Answers3

0
config.resolve = {
  alias: {
    components: path.resolve('../components/')
  }
};

alias accepts key value pairs, with value being of type string. I am not sure if it works with array.

raiyan
  • 821
  • 6
  • 15
0

To answer more specificly it would good to know where PageHeader and your webpack config is:

assuming:

  • PageHeader is in /project/pages/components
  • and your webpack config is at the root level /project

then your resolve would look something like this:

config.resolve = {
  alias: {
    components: path.resolve('./pages/components')
  }
};

again it depends on the path to your webpack config and your components directory. The path.resolve will change corresponding to that.

Sitian Liu
  • 1,156
  • 10
  • 14
0

The problem seems related to React Static Boilerplate, more specifically when the building the static pages.

I found a workaround that does the job for now. I had to prepend a ~ to the alias so it doesn't get "treated" as a node_module..

config.resolve = {
  alias: {
    "~components": path.resolve(__dirname, '../components'),
    "~decorators": path.resolve(__dirname, '../core/scripts/decorators'),
    "~helpers": path.resolve(__dirname, '../core/scripts/helpers'),
    "~i18n": path.resolve(__dirname, '../core/i18n'),
  }
};

Usage:

import fetch from '~helpers/fetch';
import header from '~components/header';

More info about this on this Github issue.

Pierre
  • 18,643
  • 4
  • 41
  • 62