Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bundle external JavaScript(from a cdn) into a React component

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

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.

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

PS: React Newbie here !

like image 468
am1704 Avatar asked Oct 11 '18 10:10

am1704


2 Answers

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. Download the external JS file and save it somewhere in the project. For example, save it to /utils folder.
  2. Just reference it and use it in the components: import { test } from '/utils/external'

2. If it's not a module:

  1. The same as above - save the file to your project.
  2. The difference is that you have to configure your module bundler to export the globals. This process is called Shimming and here's how to do it with Webpack.
  3. The same as step 2 - import { test } from '/utils/external'

* In both scenarios I assume it's a standalone external file, not being hosted somewhere as a package (npm / bower / etc.). If it's a package, instead of downloading it manually, you should use a package manager.


If you want to load it async (but not bundled):

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

like image 87
Jordan Enev Avatar answered Oct 04 '22 18:10

Jordan Enev


try something like this:

componentDidMount () {
   const script = document.createElement("script");    

   script.src = "https://cdnjs.cloudflare.com/somelibrary1.min.js";
   script.async = true;

   document.body.appendChild(script2);
 }
like image 34
Asif vora Avatar answered Oct 04 '22 17:10

Asif vora