当使用 babel、webpack 和 gulp 作为构建工具时,有没有办法单独加载 react 库文件而不是在捆绑文件中?

Is there a way to load react library files separately and not in the bundled files when using react with babel, webpack and gulp as building tool?

我有一个应用程序,我必须在其中使用 babel 构建代码并做出反应。该应用程序将使用 gulp 和 webpack 构建,以实现自动构建创建和部署。在使用gulp和webpack将babel+react代码转换为浏览器可解释代码时,我们需要使用npm安装react,并且必须在所有文件中导入,示例代码如下:

import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './helloWorld.jsx';
import HelloMe from './hello-me.jsx';

ReactDOM.render(
    <HelloWorld />,
    document.getElementById('app-test')
);

ReactDOM.render(
    <HelloMe />,
    document.getElementById('app-container')
);

现在,问题是这段代码与 webpack 捆绑在一起时,将 react 和 react-dom 库代码捆绑到捆绑文件中。因此,我将无法缓存这些要在不同视图中加载的库文件。因此,相同的库代码将在不同的捆绑文件中一次又一次地加载。 有没有办法单独加载这些文件而不是在捆绑文件中?

编辑您的 Wabpack 配置文件并将 React 和 ReactDOM 指定为外部。

externals: {
  "react": "React",
  "react-dom": "ReactDOM",
},

然后,包括来自 CDN 或您首选来源的 React 和 ReactDOM。

每当您调用 import React from 'react'require('react')(或 react-dom)时,Webpack 都会为您提供库的外部副本