如何让 webpack 解析相对于 monorepo 中包根的依赖关系?

问题描述 投票:0回答:1

我有一个yarn 3工作区monorepo,其

package.json
看起来(部分)像这样:

  "name": "myweb",
  "workspaces": [
    "client/*"
  ],

感兴趣的目录结构如下所示:

client/
  client-A/
    index.js
    src/
      components/
        AThing1.jsx
        AThing2.jsx
  client-B/
    src/
      components/
        BThing.jsx

client/client-A
内部,我们有:

// File: client-A/index.js

export { default as AThing1 } from './components/AThing1'
// File: client-A/AThing1.jsx

import AThing2 from 'components/AThing2'

client/client-B
中,有这样的:

// File: client-B/BThing.jsx

import { AThing1 } from '@myweb/client-A'

当我尝试在

client-B
中运行 webpack 5 开发服务器时,出现此错误:

ERROR in ../client-A/src/components/AThing1.jsx ...
Module not found: Error: Can't resolve 'components/AThing2' in '/workplace/termly_web/client/client-A/src/components/AThing1'

对我来说似乎很清楚它试图在

components/AThing2
中找到
client/client-B/src
,这不是我想要的。我需要它做的是在它自己的包的上下文中解析
components/AThing2
,即
client/client-A/src

client-B
webpack 似乎没有考虑
client/client-A/babel.config.js
client/client-A/webpack.config.js
中的任何内容。

我尝试将

client/client-A/src
的路径添加到
resolve.modules
webpack 配置中的
resolve.roots
client-B
数组中,但无济于事。我也尝试过
resolve.preferRelative = true
,但也没有用。

基于上面的简约示例代码,最简单的解决方案是简单地使用

import AThing2 from './components/AThing2'
,但这是不切实际的,因为我正在处理的实际目录结构相当深,并且需要大量回溯(例如
from '../../../../components/Foo' 
),这是我不愿意做的事情。我也不想更改
client-A
中的每个文件以在每次导入时使用
@myweb/
前缀。

这感觉应该是一个很容易解决的问题。我错过了什么?

这是我正在使用的配置:

// File: client/client-B/webpack.config.js
// Heavily redacted to eliminate noise...

[...snip...]

    resolve: {
      modules: [
        'src',
        'node_modules',
      ],
      roots: [
        path.resolve(__dirname, 'src'),
      ],
      extensions: ['.js', '.jsx', '.scss', '.css', '.sass'],
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: [
            {
              and: [/node_modules/],
              not: [/@mycompany\/react-components\/src/],
            },
          ],
          loader:  'babel-loader',
        },

[...snip...]
// File: client/client-B/babel.config.js

module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-react',
  ],
  plugins: [
    '@babel/plugin-proposal-class-properties',
    [
      'module-resolver',
      {
        alias: {
          'test': './test',
          'react': '../../node_modules/react',
          'react-dom': '../../node_modules/react-dom',
        },
      },
    ],
  ],
  env: {
    production: {
      plugins: [
        'transform-react-remove-prop-types',
      ],
    },
  },
}
javascript reactjs webpack yarn-workspaces
1个回答
0
投票

我正在使用 pnpm 工作区。就我而言,未解决的依赖项都是我正在使用的库的依赖项。修正者:

  • 我将所有未解决的依赖项添加到peerDependency中。
  • 在根.npmrc中添加
auto-install-peers=true
shamefully-hoist=true

它解决了我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.