关于reactjs:如何从Webpack捆绑包javascript单独加载组件?

How to load a component separately from webpack bundles javascript?

我想从我的webpack捆绑文件中将组件从外部加载到我的React应用程序中。为了阐明我的观点,这是我想要的示例HTML文件:

1
2
3
4
5
6
7
8
9
<!doctype html>
<html>
<head> ... </head>
<body>
   
    <script src="/dist/app.js">
    <script src="/external-component/timer-component.js">
</body>
</html>

我基本上希望能够加载计时器组件,但仍然要使该组件依赖于app.js(Webpack捆绑文件),因为app.js具有React。换句话说,我希望计时器组件知道React存在。我当前的计时器组件文件如下(取自ReactJS网站):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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不存在。如果我尝试导入React:

1
2
3
 const React = require('react');
 // or
 import React from 'react';

我收到一个要求(或导入)未定义的错误。正确的做法是什么?我的理解是webpack app.js文件创建了名称空间,因此React组件并没有真正看到外界。仅webpack文件中的组件请参见React。如果是这种情况,我该如何向外界曝光?


在app.js中的某个地方,将react声明为全局变量。
window.React = React

这样,您可以从其他组件访问它。

执行此操作的另一种方法是外部化webpack构建的反应,并通过页面中的脚本标签将其包括在内。

要外部化反应,请将其包含在您的webpack配置中
externals: {'react': 'React'}

将此内容包含在您的html中以进行全局响应。

1
2
<script src="https://unpkg.com/react@15/dist/react.js">
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js">

我认为您想为Webpack使用"脚本加载程序"插件。我用它来做到这一点,并且效果很好。

https://github.com/webpack/script-loader

这是一种将所有内容都排除在index.html之外,并将所有需求都放在一个位置的好方法,例如我的种子项目index.js包含了所有这些内容,而在其他项目中,我所要做的就是在需要时在此处添加脚本。他们甚至不必安装npm,您只需在项目中包含一个脚本并将其加载到捆绑包中即可。

(我的一个使用webpack的脚本加载器的项目)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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');