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

前端 未结 4 546
北恋
北恋 2021-02-05 21:08

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

4条回答
  •  不思量自难忘°
    2021-02-05 21:53

    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.

提交回复
热议问题