Recursive import of components using webpack in Re

2019-08-31 17:52发布

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.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-31 18:17

You can do this

In webpack config

alias: {
  components: 'components', // base path to components
},

In your code

import Header from 'components/header'
import Footer from 'component/footer'

Hope this helps!

查看更多
老娘就宠你
3楼-- · 2019-08-31 18:32

In your src folder you should have the structure similar to this:

src
└ scenes
  ├ components
  │ ├ ComponentA
  │ │ └ ComponentA.jsx
  │ └ ComponentB
  │   └ ComponentB.jsx
  └ main
    ├ components
    │ └ App
    │   ├ components
    │   │ ├ ComponentC
    │   │ │ └ ComponentC.jsx
    │   │ └ ComponentD
    │   │   └ ComponentD.jsx
    │   └ App.jsx
    └ index.jsx

In your webpack.config.js you should have the following (Webpack 3):

const DirectoryNamedWebpackPlugin = require('directory-named-webpack-plugin');
...
let config = {
  ...
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      }
    ]
  },
  resolve: {
      modules: ['components', 'node_modules'],
      extensions: ['.js', '.jsx'],
      plugins: [
          new DirectoryNamedWebpackPlugin(true)
      ]
  }
  ...
}
modules.exports = config;

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 in node_modules folder and you can include components by their names.
E. g. in src/scenes/main/index.jsx you can simply write:

import App from 'App';

in src/scenes/main/components/App/App.jsx you can write:

import ComponentC from 'ComponentC';
import ComponentD from 'ComponentD';

and in src/scenes/main/components/App/components/CompoentC/ComponentC.jsx you can write:

import ComponentA from 'ComponentA';
import ComponentB from 'ComponentB';

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 see ComponentA.jsx, ComponentB.jsx.

查看更多
登录 后发表回答