gpt4 book ai didi

reactjs - 网页包 + `create-react-app` | ProvidePlugin 未将 React 作为模块加载

转载 作者:行者123 更新时间:2023-12-03 23:51:45 26 4
gpt4 key购买 nike

* 注意:我对 Webpack 几乎一无所知。

我想加载 react节点模块和 Webpack 中的其他模块通过 ProvidePlugin可以在全局范围内访问它们。

我创建了一个 create-react-app并运行 eject并获得了 Webpack create-react-app 的预定义配置提供。

我读了this post关于加载react全局通过 PluginProvidor并阅读 PluginProvidor本身在Webpack docs ,其中后者指出:

By default, module resolution path is current folder (./**) and node_modules



基于此,在 webpack.config.js , 在 plugins ,我添加了以下 PluginProvidor :
...
plugins: [
new webpack.ProvidePlugin(
{
React: 'react'
}
)
]
...

但它不起作用 - 在 JSX 文件中,当我调用 React 时(例如 class MyComponent extends React.Component { ... } )我收到一个错误,指出 React 未定义(还有一个 React 特定错误,必须在 JSX 文件中定义 React) .

为什么它不起作用?据我了解,我给出了我在 JSX 文件中调用的相同标识符,就像我提到的,根据 Webpack 文档,给 react 的路径。 node_modules 中的模块- 两者都需要它工作。

我的配置文件: webpack.config.js

最佳答案

它是 not a good idea使用 ProvidePlugin 和 even worseeject你的税务局。

而不是 ProvidePlugin使用全局变量:

// globals.js
import React from 'react';

window.React = React;

然后 import './globals'
import './globals';

// no need import React
import ReactDOM from 'react-dom';
...

如需将插件添加到 CRA 网页包,请参阅 react-app-rewired .

添加插件示例:

/* config-overrides.js */
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = function override(config, env) {
if (!config.plugins) {
config.plugins = [];
}
config.plugins.push(new MonacoWebpackPlugin());
return config;
};

演示:

Edit modest-meninsky-brb7y

关于reactjs - 网页包 + `create-react-app` | ProvidePlugin 未将 React 作为模块加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56587699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com