【问题标题】:Webpack resolve index.whatever.jsx automaticallyWebpack 自动解析 index.whatever.jsx
【发布时间】:2017-10-22 17:05:27
【问题描述】:

当使用 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

但仍允许像上面这样的速记导入?


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

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

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

【问题讨论】:

    标签: reactjs module webpack components jsx


    【解决方案1】:

    这个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 是如何工作的,这就是为什么我将两个可能的路径作为数组返回。用它做一些实验,你将能够找到正确的返回路径。

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

    【讨论】:

      【解决方案2】:

      你必须使用文件夹/index.js 结构吗?你可以让 thing.js 存在于 /component 文件夹中,这样你就可以使用 webpack resolve 像上面那样以速记方式导入内容:

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

      webpack 解析看起来像这样:

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

      【讨论】:

      • 我正在尝试将我的组件分开到它们自己的文件夹中以保持结构清洁。
      猜你喜欢
      • 2018-11-01
      • 2017-10-13
      • 2018-03-19
      • 2018-02-17
      • 2017-08-07
      • 2016-10-18
      • 2020-09-11
      • 2016-08-15
      • 2017-07-27
      相关资源
      最近更新 更多