首页 > 解决方案 > 使用来自 webpack 的构建包时反应钩子错误

问题描述

我已经制作了一个库并尝试通过这样做在示例代码上使用内置包

import { createMiddleware, useActionListener } from "../../../../lib";

它发生Invalid hook call.

  useActionListener("SUB", (action) => {
    //...
  });

所以我尝试发布一个包并像这样更改

import { createMiddleware, useActionListener } from "myLibraryName";

它就像魅力一样。

我不知道为什么直接调用构建包会发生错误。有任何想法吗?

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'lib'),
    filename: 'index.js',
    libraryTarget: 'umd',
    library: 'reactActionListener',
    globalObject: 'this',
  },
  externals: {
    react: {
      root: 'React',
      commonjs2: 'react',
      commonjs: 'react',
      amd: 'react',
    },
    redux: {
      root: 'Redux',
      commonjs2: 'redux',
      commonjs: 'redux',
      amd: 'redux',
    },
  },
  resolve: {
    extensions: ['.ts', '.js', '.json', '.tsx', '.jsx'],
    alias: {
      // Needed when library is linked via `npm link` to app
      react: path.resolve('./node_modules/react'),
    },
  },
  mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
  module: {
    rules: [
      {
        test: /\.(js|ts|tsx|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
    ],
  },
};

标签: reactjswebpackreact-hooks

解决方案


推荐阅读