Pierre Pierre - 5 months ago 41
Javascript Question

How do I create a webpack import alias in React Static Boilerplate?

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

Answer Source

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.