通过url加载的es6模块无法访问“useState”,因为它是未定义的

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

我正在使用 webpack 构建 React 库,并且该库正确构建到

es6
模块中。然后,我们尝试将此模块托管在 CDN 上,以便我们可以通过
url
而不是
node_modules
导入它。

然后我们像这样导入它,我得到了正确的项目。

import('http://example.com/test.js').then(m => console.log(m.default));

该库有一个测试组件,当我在应用程序中显示它时,它可以工作:

这是通过库导出的:

export default ({ name }) => {
  return <div>{name}</div>;
};

应用程序会像这样实现它:

export default () => {
  const [Test, setTest] = useState();

  useEffect(() => {
    import('http://example.com/test.js').then(m => setTest(m.default));
  }, []);

  return <Test name="Joe" />;
}

但是,当我添加

useState
时,就像这样:

import { useState } from 'react';
export default ({ name }) => {
  const [displayName] = useState('Billy');
  return <div>{displayName}</div>;
};

然后我得到这两个错误:

test.tsx:12 Warning: 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
react.development.js:1623 Uncaught TypeError: Cannot read properties of null (reading 'useState')
    at useState (react.development.js:1623:21)
    at default (test.tsx:12:76)

我的网页包看起来像这样:

export default {
  // module rules and entry snipped out

  output: {
    path: path.resolve(__dirname, '../../dist'),
    filename: 'test.js',
    library: {
      type: 'module',
    },
  },
  experiments: {
    outputModule: true,
  }
}

当我将

externals: ['react', 'react-dom']
添加到 webpack 时,我收到此错误:

Uncaught (in promise) TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

为什么我的库在通过 URL 加载时无法使用

useState

javascript reactjs webpack
1个回答
0
投票

看起来您还没有从库中排除 React 包

//webpack.config.js
externals: {
 'react': 'react', 
 'react-dom' : 'reactDOM'
}
© www.soinside.com 2019 - 2024. All rights reserved.