【问题标题】:How to to change the default file from index to a custom in React Components?如何在 React 组件中将默认文件从索引更改为自定义文件?
【发布时间】:2021-09-01 03:32:47
【问题描述】:

项目的结构一般是这样的:

 components
 - my-component
 - - my-component.ts
 - - index.ts

其中 index.(ts/js) 总是包含

import MyComponent from './my-component';
export default MyComponent;

我想删除 index.(js/ts) 并仍然使用路径导入/需要我的组件

import MyComponent from './components/my-component' // not having the index file!
// Please, do not suggest importing them like this
import MyComponent from './components/my-component/my-component'

我使用 Webpack 5。我知道 Webpack 4 有一个 module,但它不适用于 5。

我希望 NodeJS/Webpack 查找自定义文件名而不是索引。

【问题讨论】:

  • 索引文件在导入语句中被省略,如果你想用一个特定的名称导入它们,你可以重命名它们。这有什么用例?
  • 我想要一个文件 components/my-component/my-component.ts,而不是 index.ts。然后我想导入那些我会导入 index.ts

标签: javascript node.js reactjs typescript webpack


【解决方案1】:

其他一些解决方案:

  • 您可以将components/my-component/my-component.ts 移动到components/my-component.ts。我假设您有理由不这样做(大概是该组件目录中的其他文件)。
  • 您可以使用resolve.alias 并列出您想要的所有映射:
module.exports = {
  //...
  resolve: {
    alias: {
      "./components/my-component": path.resolve(__dirname, 'components/my-component/my-component.js'),
      //...
    },
  },
};

【讨论】:

  • 这很接近。也不能移动文件 ../my-component.ts,因为我有 css 和其他文件。
  • 别名很好,但我希望每个组件都像这样工作,并避免为每个新组件更改 webpack 配置。我不完全确定 DirectoryNamedWebpackPlugin 不适用于 5,但在我的项目中,我得到了类似“无法解析 './components/my-component' in ...”的信息
  • 也许我设置错了:(我把它放在 module.exports.plugins[] 和 module.exports.resolve.plugins[] 中,但仍然遇到同样的错误
猜你喜欢
  • 2010-10-05
  • 2012-12-20
  • 2021-07-08
  • 2016-01-25
  • 2023-04-09
  • 1970-01-01
  • 2015-04-14
  • 2015-01-21
  • 2012-12-08
相关资源
最近更新 更多