1

I'm working on a React app that's NOT built with create-react-app and trying to work with Webpack to make absolute imports work. The app structure looks like this:

.
├── package-lock.json
├── package.json
├── public
│   └── index.html
├── src
│   ├── actions
│   ├── components
│   │   └── App.js
│   ├── index.css
│   ├── index.js
│   ├── reducers
│   │   └── index.js
│   ├── storage
│   │   └── index.js
│   └── store.js
└── webpack.config.js

The reason I have the store.js file and also the storage directory is because the absolute import is not working (that's why I'm making it work by relative importing from store.js). The following is what I'm doing in my webpack.config.js for the absolute import, as per their docs and other SO threads:

resolve: {
        alias: {
            src: path.resolve(__dirname, 'src/'),
        },
        extensions: ['.js']
},

However, I keep getting the following error despite adding the rule:

ERROR in ./src/storage/index.js
Module not found: Error: Can't resolve './reducers' in '/my-project/src/storage'

I'm simply doing an import rootReducer from './reducers'; from the storage/index.js file, where the error is coming from. What would be a good way to configure the webpack.alias object correctly in this case?

complexSandwich
  • 493
  • 2
  • 9
  • 23
  • It should be `import rootReducer from '../reducers';`. – Prakash Sharma Nov 12 '19 at 18:32
  • thanks, it's still broken though. I want to do just `reducers` and not `../reducers`. Implmenting absolute import would let me do that. – complexSandwich Nov 12 '19 at 18:39
  • 1
    You are using webpack alias. In that case you should import it with the alias name `import rootReducer from 'src/reducers';` If you want to import just `reducers` then you need to add the alias like `reducers: path.resolve(__dirname, 'src/reducers'),` – Prakash Sharma Nov 12 '19 at 18:53
  • Possible duplicate [absolute imports](https://stackoverflow.com/q/45213279/2969544) – oklas Mar 13 '20 at 06:32

2 Answers2

2

as Prakash pointed out above, here's what I needed to do:

resolve: {
        alias: {
            components: path.resolve(__dirname, 'src/components'),
            reducers: path.resolve(__dirname, 'src/reducers')
        },
        extensions: ['.js']
    },
complexSandwich
  • 493
  • 2
  • 9
  • 23
0

You can wrap your code into node_modules in src directory and you can import from src as from root

.
├── package-lock.json
├── package.json
├── public
│   └── index.html
├── src
│   └── node_modules
│       ├── actions
│       ├── components
│       │   └── App.js
│       ├── index.css
│       ├── index.js
│       ├── reducers
│       │   └── index.js
│       ├── storage
│       │   └── index.js
│       └── store.js
└── webpack.config.js

import App from 'components/App'

Dandgerson
  • 81
  • 1
  • 8