将外部 JavaScript(来自 cdn)捆绑到 React 组件中 [英] Bundle external JavaScript(from a cdn) into a React component

查看:36
本文介绍了将外部 JavaScript(来自 cdn)捆绑到 React 组件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有哪些选项可以将外部 javascript sdk 捆绑到 React 组件中?

What options are there to bundle an external javascript sdk into a React Component?

我尝试在 index.html 中包含 javascript 并通过 window.xyz 引用它.它运行良好,但我无法进行生产构建,因为 javascript 没有以这种方式打包.

I have tried including the javascript in the index.html and referring to it through window.xyz . It works well but I can't do a production build since the javascript is not packaged in this way.

有没有办法简单地将一个 javascript 文件导入到 React 组件定义中?

Is there a way to simply import a javascript file into the React Component definition?

PS:在这里反应新手!

PS: React Newbie here !

推荐答案

如果您希望将脚本捆绑在构建中,您有两个选择:

1.如果外部文件是模块,我会按如下方式处理:

If you want the script to be bundled in the build, you have 2 options:

1. If the external file is a module, I would approach it as follows:

  1. 下载外部 JS 文件并将其保存在项目中的某个位置.例如,将其保存到 /utils 文件夹.
  2. 只需引用它并在组件中使用它:import { test } from '/utils/external'

2.如果不是模块:

  1. 同上 - 将文件保存到您的项目中.
  2. 不同之处在于您必须配置模块捆绑器以导出全局变量.这个过程称为Shimming这里是如何做到的网络包.
  3. 同步骤 2 - import { test } from '/utils/external'

* 在这两种情况下,我都假设它是一个独立的外部文件,而不是作为包(npm/bower/等)托管在某处.如果是包,不要手动下载,而应该使用包管理器.

按照 @Paras 回答,他建议使用库进行脚本异步延迟加载.

Follow the @Paras answer, where he suggests for using a library for script async lazy loading.

这篇关于将外部 JavaScript(来自 cdn)捆绑到 React 组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆