Webpack 自动解析 index.whatever.jsx

Webpack resolve index.whatever.jsx automatically

当使用 webpack 解析我的导入时:

/component/thing/index.jsx
/component/stuff/index.jsx

可以像

一样导入
import Thing from './component/thing';
import Stuff from './component/stuff';

因为 index.jsx 是自动解析的。问题是现在我的项目中有大量名为 index.jsx 的文件,这使得搜索文件变得困难且烦人。有没有办法配置 webpack 接受类似的东西:

/component/thing/thing.index.jsx
/component/stuff/stuff.index.jsx

但仍允许 shorthand 像上面那样导入?


我的第一直觉是(在 Webpack 中):

resolve: {
  extensions: ['.index.jsx']
}

但这并没有解决。是否可以做我正在寻找的事情?

这个resolver plugin可能对你有帮助。

我没试过。但是根据描述,你应该可以做这样的事情。

resolve: {
  plugins: [
    new DirectoryNamedWebpackPlugin({
      transformFn: function(dirName) {
        // use this function to provide custom transforms of resolving directory name 
        // return desired filename or array of filenames which will be used 
        // one by one (honoring order) in attempts to resolve module 
        return [dirName + ".index", dirName + "/" + dirName + ".index"]
      }
    })
  ]
}

我不确定这个 transformFn 是如何工作的,这就是为什么我 return 两个可能的路径作为一个数组。用它做一些实验,你将能够在你的情况下找到 return 的正确路径。

此外,请确保您使用的是基于您的 webpack 版本的 correct version 插件。

一定要用folder/index.js结构吗?您可以将 thing.js 放在 /component 文件夹中,这样您就可以像上面那样使用 webpack resolve 导入 shorthand 中的内容:

import Thing from 'component/thing';
import Stuff from 'component/stuff';

webpack 解析看起来像这样:

resolve: { 
    modules: [__dirname, 'node_modules'], 
    extensions: ['.js'] 
}