mayk93
mayk93

Reputation: 1537

How to set up home path in webpack

I have a React project and I am using webpack to generate a bundle.

In my components, I reference other components using relative paths.

For example, if I have a structure like this, this is how my imports would look:

- src
   - actions
   - components
         - my_component

If I wanted to import a action in my_component, I would do this.

import {my_action} from ../actions

I am telling my component go up one level, go into actions and pick up my_action from there.

I know it is possible to do imports like this:

import {my_action} from @/actions

I want to say from the root directory, go into actions and pick up my_action from there.

My question is, how do I make @ usable as project root in my project?

Thanks!


Edit 1

I started my app with create-react-app and ejected. I retained the structure though, so I have something like this:

- frontend
    - config
        - webpack.config.dev
        - webpack.config.prod
    - src
        - actions
        - my_components

Because of this structure, I added this in both webpack.config files.

let up = path.resolve(__dirname, '..');
let src_path = path.resolve(up, 'src');

I logged src_path and it looked correct to my, namely, it was something like this.

/path/to/my/project/frontend/src

I had to do it like this because simply doing path.resolve(__dirname, "src") ended up with /path/to/my/project/frontend/config/src, which is obviously incorrect.

Even though I export context: src_path, I still get this error:

Module not found: Can't resolve '~/actions' in '/path/to/my/project/frontend/src/my_components'

Am I perhaps doing something wrong with my path.resolve?

Upvotes: 1

Views: 1914

Answers (2)

Martin
Martin

Reputation: 201

The best practice to put your webpack.config.js file in frontend directory and you shouldn't do this:

let up = path.resolve(__dirname, '..'); let src_path = path.resolve(up, 'src');

Just do this:

let src_path = path.resolve(__dirname, 'src');

For using short file or module name you should define aliases using resolve.alias in webpack.config.js.

For example:

resolve: { alias: { Actions: './actions', //OR ActionFirst: './actions/action-first', },

And You can use this alias:

import ActionFirst from 'Actions/action-first'; //OR import ActionFirst from 'ActionFirst';

Upvotes: 4

Adel Helal
Adel Helal

Reputation: 680

With React and ES6 you can even do the following:

import {my_action} from '~actions';

To achieve that is in your webpack.config.js file, by setting context as one of the exported properties:

context: path.resolve(__dirname, './src')

You can read more here: https://webpack.js.org/configuration/entry-context/

Upvotes: 0

Related Questions