简体   繁体   English

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

[英]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?

I have an application where I have to build code using babel and react. 我有一个应用程序,我必须使用babel构建代码并做出反应。 The application will be built using gulp and webpack for automated build creation and deployment. 该应用程序将使用gulp和webpack构建,以实现自动构建和部署。 When using gulp and webpack to convert babel+react code to browser interpretable code, we need to install react using npm and has to be imported in all files, following is the sample code: 当使用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')
);

Now, the problem is this code when bundled with webpack, bundles react and react-dom library code to the bundled file. 现在,问题是这个代码与webpack捆绑在一起时,bundle会对库文件代码做出反应并将其反应到捆绑文件中。 So, I would not be able to cache these library files to be loaded in different views. 因此,我无法将这些库文件缓存到不同视图中加载。 Due to this, the same library code will load again and again in different bundled files. 因此,相同的库代码将在不同的捆绑文件中反复加载。 Is there a way to load these files separately and not in the bundled file? 有没有办法单独加载这些文件而不是在捆绑文件中?

Edit your Wabpack configuration file and specify React & ReactDOM as externals. 编辑Wabpack配置文件并将React和ReactDOM指定为外部。

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

Then, include React & ReactDOM from CDN or your prefered source. 然后,包括来自CDN的React和ReactDOM或您喜欢的来源。

Whenever you call import React from 'react' or require('react') (or react-dom), Webpack gives you external copy of library 无论何时import React from 'react'require('react') (或react-dom)调用import React from 'react' ,Webpack都会为您提供库的外部副本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM