Рабочие пространства пряжи и неправильный вызов крюка - PullRequest
2 голосов
/ 17 апреля 2020

Возникли большие проблемы при попытке настроить общую библиотеку пользовательского интерфейса.

Я настроил рабочую область пряжи, которая выглядит следующим образом:

/monorepo
   /common-16.13
   /react-app-16.8.
   /another-app-16.13

Затем я импортирую common-16.13 в react-app-16.8 и использую один из компонентов, таких как:

 /react-app/home.js
    import {SharedComponent} from "common"

Однако, когда я запускаю приложение, я получаю эту ошибку:

react.development.js?80c6:1465 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

Внутри общего я имею:

/ src / components / SharedComponent.jsx:

    import React from 'react';
    import { Box } from 'material-ui/core';
    export const ShareComponent = ()=> <Box>SharedComponent</Box>;

/ src / components / index. js:

   export { SharedComponen t} from 'SharedComponent';

/ src / index. js:

   export {SharedComponent } from './components';

пакет. json:

  {  
       "name": "@libs/common",
       "main": "dist/index.js",
       "scripts" {
          "build": "webpack"
       }
  }

/common/webpack.config.json: 

    const webpack = require('webpack');

    module.exports = env => {
        // Each key value generate a page specific bundle
        entry: {
          index: './src/index.js'
        },

        output: {
          path: path.resolve(ROOT_PATH, 'dist'),
          publicPath: '/',
          filename: 'index.js',
          library: '@libs/common',
          libraryTarget: 'umd'
        },

        module: {
          rules: [
            {
              test: /\.(js|jsx)$/,
              use: 'happypack/loader?id=jsx',
              exclude: /node_modules/
            }
          ]
        },
        // Automatically resolve below extensions
        // Enable users to leave off the extensions when importing
        resolve: {
          symlinks: false,
          extensions: ['*', '.js', '.jsx', '.css', '.scss']
        },

        plugins: [
          new HappyPack({
            id: 'css',
            threadPool: happyThreadPool,
            loaders: [
              'cache-loader',
              'style-loader',
              {
                loader: MiniCssExtractPlugin.loader,
                options: {
                  hmr: true
                }
              },
              'css-loader',
              'sass-loader'
            ]
          }),
          new HappyPack({
            id: 'jsx',
            threadPool: happyThreadPool,
            loaders: [
              'cache-loader',
              {
                loader: 'babel-loader'
              }
            ]
          })
        ]
      }

Так что я связываю общее. Затем в моем приложении-реактиве я установил @ lib / common. Затем я импортирую SharedComponent в свое реактивное приложение:

/ react-app / src / index. js:

   import { SharedComponent } from '@libs/common';

/ реагировать-app / webpack.config. js:

{
  // Each key value generate a page specific bundle
  entry: {
    index: './src/index.jsx',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },

    ]
  },
  // Automatically resolve below extensions
  // Enable users to leave off the extensions when importing
  resolve: {
    extensions: ['*', '.js', '.jsx', '.css', 'scss'],
    alias: {
      react: path.resolve('./node_modules/react'),
    }
  },
  output: {
    path: path.resolve(ROOT_PATH, 'dist'),
    publicPath: '/',
    filename: '[name].bundle.js',
    chunkFilename: '[id].bundle.js'
  },
};

Он отлично работает, но когда я запускаю приложение, я сталкиваюсь с ошибкой выше. Я не могу сказать, связано ли это с тем, как я экспортирую свои общие компоненты, но это кажется правильным. Я прочитал, что в моем приложении должен быть псевдоним реакции, что я и делаю. Я использую рабочие области пряжи и не уверен, что это как-то связано.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...