我想从我的 webpack 捆绑文件外部将组件加载到我的 React 应用程序中。为了详细说明我的观点,这里有一个我想要的示例 HTML 文件:
<!doctype html>
<html>
<head> ... </head>
<body>
<div id="app"></div>
<script src="/dist/app.js"></script>
<script src="/external-component/timer-component.js"></script>
</body>
</html>
我基本上希望能够加载计时器组件,但仍然使该组件依赖于app.js
(webpack 捆绑文件),因为app.js
有 React。换句话说,我希望计时器组件知道 React 的存在。我当前的计时器组件文件如下(取自 ReactJS 网站):
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { secondsElapsed: 0 };
}
tick() {
this.setState(prevState => ({
secondsElapsed: prevState.secondsElapsed + 1
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return React.createElement(
"div",
null,
"Seconds Elapsed: ",
this.state.secondsElapsed
);
}
}
我不断收到 React 不存在的错误。如果我尝试导入反应:
const React = require('react');
// or
import React from 'react';
我收到一个错误,要求(或导入)未定义。正确的方法是什么?我的理解是 webpack app.js 文件创建命名空间,所以 React 组件并没有真正看到外部世界。只有 webpack 文件中的组件才能看到 React。如果是这样的话,我该如何向外界暴露反应?
在应用中的某个地方.js,将 react 声明为全局变量。 window.React = React
这样,您可以从其他组件访问它。
另一种方法是从 webpack 构建中外部化 react 并通过页面中的脚本标签将其包含在内。
要外部化反应,请将其包含在您的 webpack 配置中 externals: {'react': 'React'}
将其包含在您的 html 中以全局访问反应。
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
我想你想在 Webpack 中使用"脚本加载器"插件。我用它来做到这一点,效果很好。
https://github.com/webpack/script-loader
这是将所有内容排除在索引之外的好方法.html并将所有需求放在一个地方,例如我的种子项目索引.js其中包含所有这些内容,而在其他项目中,我所要做的就是在需要时在此处添加脚本。它们甚至不必安装 npm,您只需在项目中有一个脚本并以这种方式将其加载到捆绑包中即可。
(我使用 webpack 的脚本加载器的一个项目)
require('!!script!core-js/client/shim.js');
require('!!script!zone.js/dist/zone.js');
require('!!script!reflect-metadata/temp/Reflect.js');
require('!!script!rxjs/bundles/Rx.js');
require('!!script!@angular/core/bundles/core.umd.js');
require('!!script!@angular/common/bundles/common.umd.js');
require('!!script!@angular/compiler/bundles/compiler.umd.js');
require('!!script!@angular/platform-browser/bundles/platform-browser.umd.js');
require('!!script!@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js');
require('!!script!@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js');
require('!style!css!./css/styles.css');
require('!style!css!./css/animate.css');
require('!style!css!bootstrap/dist/css/bootstrap.css');
require('./app/main');