在从CDN加载的React中使用外部依赖项

在从CDN加载的React中使用外部依赖项

本文介绍了在从CDN加载的React中使用外部依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对ReactJS相对较新,并且将其用于现有应用程序中的某些交互式元素.我从CDN导入React和ReactDOM:

I'm relatively new to ReactJS and am using it for certain interactive elements within an existing app. I import React and ReactDOM from a CDN:

<script src="https://unpkg.com/react@16/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" crossorigin></script>

然后我在Babel转换的某些.js文件中用JSX写我的ReactJS,然后像这样导入:

And I write my ReactJS in JSX in some .js files that Babel translates and I import like this:

<script src="/static/react/NameScores.js"></script>

我的问题是我有时想使用外部依赖关系,而我一生都无法弄清楚如何正确导入它们.

My problem is that I would sometimes like to use external dependencies and I cannot for the life of me figure out how to import them properly.

例如,我想使用react-card-flip.它似乎有一个CDN,所以我将其导入为:

For example, I want to use react-card-flip. It appears to have a CDN, so I import it like so:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-card-flip/1.0.10/ReactCardFlip.min.js"></script>

但是它不起作用.我得到一个 ReactCardFlip.min.js:1 Uncaught ReferenceError:导出未定义在ReactCardFlip.min.js:1 错误处.

But it doesn't work. I get a ReactCardFlip.min.js:1 Uncaught ReferenceError: exports is not defined at ReactCardFlip.min.js:1 error.

如何在基于CDN的设置中利用外部依赖关系?我必须使用NPM吗?我已经尝试过了,但是无法通过NPM使React正常工作,而CDN却要容易得多.

How can I make use of external dependencies with my CDN-based setup? Do I have to use NPM? I have tried, but could not get React to work via NPM, and the CDN is just much easier.

谢谢

推荐答案

最后,在与NPM进行了很多努力之后,我决定使用浏览以将NPM模块直接导入到我的javascript中.它可以很好地满足我的需求.

In the end, after much struggle with NPM, I decided to use Browserify to import NPM modules directly into my javascript. It works beautifully for what I need.

通过将多个javascript文件捆绑到一个文件( bundle.js )中来工作.这样做时,它将扫描代码中的 require(...)(无效的javascript),导入相关模块并将其直接放入 bundle.js

It works by bundling multiple javascript files into one single file (bundle.js). As it does so, it scans through the code for require(...) (which is invalid javascript), imports the relevant module and places this directly into bundle.js.

我使用 Watchify 自动执行此过程.正在运行的脚本会密切注意我的代码更改,然后自动在其上运行Browserify.

I use Watchify to automate this process. A running script keeps an eye out for changes to my code, then runs Browserify on it automatically.

例如,如果我想使用 react-string-replace ,我只需执行以下操作:

For example, if I want to use react-string-replace, I simply do something like this:

const reactStringReplace = require('react-string-replace')

mergedPhrase = reactStringReplace(
 mergedPhrase,
 lookup,
 (match, k) => (
 replacement
 )
)

这篇关于在从CDN加载的React中使用外部依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:14