Each time I have to import a Component, I can either use its absolute path :
import ProductDescription from '../../ProductDescription';
or define an alias in my webpack.config.js
file :
alias: {
app: 'components/app',
home: 'components/home',
utility: 'components/common/utility',
textService: 'services/textService'
},
So that I can import like this :
import Home from 'home';
import Utility from 'utility';
Now obviously, both work fine, but both are shite. Is there a way to recursively configure my webpack so that it resolves all files within my /src
directory ?
I've tried using the modules
option like this :
modules: ['node_modules', 'src', paths.appNodeModules]
But this failed miserably.
You can do this
In webpack config
In your code
Hope this helps!
In your
src
folder you should have the structure similar to this:In your
webpack.config.js
you should have the following (Webpack 3):As a result of using the above configuration and folder structure webpack will search for components in
components
folders recursively in the same way it searches for Node modules innode_modules
folder and you can include components by their names.E. g. in
src/scenes/main/index.jsx
you can simply write:in
src/scenes/main/components/App/App.jsx
you can write:and in
src/scenes/main/components/App/components/CompoentC/ComponentC.jsx
you can write:P. S. I use the plugin directory-named-webpack-plugin to allow webpack to recognize files named after their parent folders as default entry points for components so in my IDE tabs' names I would not see
ComponentA/index.jsx
,ComponentB/index.jsx
and instead seeComponentA.jsx
,ComponentB.jsx
.