【问题标题】:Absolute import using Webpack resolve.alias in a React app在 React 应用程序中使用 Webpack resolve.alias 进行绝对导入
【发布时间】:2020-03-08 12:04:32
【问题描述】:

我正在开发一个不是使用 create-react-app 构建的 React 应用程序,并尝试使用 Webpack 来实现绝对导入。应用结构如下所示:

.
├── package-lock.json
├── package.json
├── public
│   └── index.html
├── src
│   ├── actions
│   ├── components
│   │   └── App.js
│   ├── index.css
│   ├── index.js
│   ├── reducers
│   │   └── index.js
│   ├── storage
│   │   └── index.js
│   └── store.js
└── webpack.config.js

我拥有store.js 文件和storage 目录的原因是因为绝对导入不起作用(这就是为什么我通过从store.js 进行相对导入来使其工作)。根据他们的文档和其他 SO 线程,以下是我在 webpack.config.js 中为绝对导入所做的事情:

resolve: {
        alias: {
            src: path.resolve(__dirname, 'src/'),
        },
        extensions: ['.js']
},

但是,尽管添加了规则,我仍然收到以下错误:

ERROR in ./src/storage/index.js
Module not found: Error: Can't resolve './reducers' in '/my-project/src/storage'

我只是从storage/index.js 文件中执行import rootReducer from './reducers';,错误来自该文件。在这种情况下,正确配置 webpack.alias 对象的好方法是什么?

【问题讨论】:

  • 应该是import rootReducer from '../reducers';
  • 谢谢,不过还是坏了。我只想做reducers 而不是../reducers。实现绝对导入会让我做到这一点。
  • 你正在使用 webpack 别名。在这种情况下,您应该使用别名 import rootReducer from 'src/reducers'; 导入它。如果您只想导入 reducers,那么您需要添加别名,如 reducers: path.resolve(__dirname, 'src/reducers'),
  • 可能重复absolute imports

标签: javascript reactjs webpack path


【解决方案1】:

正如 Prakash 上面指出的,这就是我需要做的:

resolve: {
        alias: {
            components: path.resolve(__dirname, 'src/components'),
            reducers: path.resolve(__dirname, 'src/reducers')
        },
        extensions: ['.js']
    },

【讨论】:

    【解决方案2】:

    您可以将代码包装到src 目录下的node_modules 中,并且可以从根目录中的src 导入

    .
    ├── package-lock.json
    ├── package.json
    ├── public
    │   └── index.html
    ├── src
    │   └── node_modules
    │       ├── actions
    │       ├── components
    │       │   └── App.js
    │       ├── index.css
    │       ├── index.js
    │       ├── reducers
    │       │   └── index.js
    │       ├── storage
    │       │   └── index.js
    │       └── store.js
    └── webpack.config.js
    

    import App from 'components/App'

    【讨论】:

      猜你喜欢
      • 2018-03-21
      • 2019-12-03
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 2017-01-19
      • 2016-06-26
      • 2019-03-31
      • 2018-11-10
      相关资源
      最近更新 更多