最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Bundle external JavaScript(from a cdn) into a React component - Stack Overflow

programmeradmin2浏览0评论

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 !

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 !

Share Improve this question edited Oct 29, 2021 at 11:09 Ahmet Emre Kilinc 6,89519 gold badges36 silver badges47 bronze badges asked Oct 11, 2018 at 10:07 am1704am1704 8571 gold badge6 silver badges15 bronze badges 3
  • I have tried searching this (ovbiously) on internet and stackoverflow in particular but have not found a well received answer to this, hence posting it as a fresh question. – am1704 Commented Oct 11, 2018 at 10:08
  • What is the library in particular you want to use ? – H S Commented Oct 13, 2018 at 15:19
  • @asynts .js file in a .jsx file – am1704 Commented Oct 13, 2018 at 20:56
Add a comment  | 

4 Answers 4

Reset to default 6 +25

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.

To load external scripts from a CDN, a good option is to use the react-async-script-loader library. Not only can it load external JS files asynchronously, but it also loads on demand, i.e., lazy loading and supports both parallel and sequential loading.

It allows you to decorate your component using an HOC like so:

export default scriptLoader(
  [
    'https://cdnjs.cloudflare.com/somelibrary1.min.js',
    'https://cdnjs.cloudflare.com/somelibrary2.min.js'
  ]
)(YourComponent)

Actually you should know about the entire approach then see the codes.

You must make a separate folder for your alternative cdn JavaScript files which they are out of files that webpack build them. Then paste these files into this folder and after all import them as externals into webpack configuration.

Then config them as vendor files, and absolutely output file name should make dynamically, so the webpack build its bundle and then copy your JavaScript files into dist folder. follow below:

// webpack.configuration.js
~~~
module.exports = {
    ~~~
    externals: {
        cdnFileOne: `${srcRoot}/outFiles/cdnFile1.js`,
        cdnFileTwo: `${srcRoot}/outFiles/cdnFile2.js`,
    },
    ~~~
};

Sounds good, now you have external names for JavaScript files and import it into webpack configuration as a externals config.

Now you should put them in entry to import them as separate files:

// webpack.configuration.js
~~~
module.exports = {
    ~~~
    entry: {
        cdnFiles: ['cdnFileOne', 'cdnFileTwo'], <-- cdn files
        app: `${srcRoot}/app/index.js`, // <-- its your own codes
    },
    output: {
        path: '/dist',
        filename: '[name].js' // <== dynamically make your JavaScript files,
                              //      so, in dist folder you can see app.js and
                              //      cdnFiles.js file
    }
    ~~~
};

Surly, you must add bundles to your HTML template:

  ~~~
  res.status(200).send(`
    <!doctype html>
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        ${styles}
        ${title}
      </head>
      <body>
        <div id="root">${ssrHTML}</div>
        <script src="app.js" defer></script>
        <script src="cdnFiles.js" defer></script>
      </body>
    </html>
 `);
~~~

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);
 }
发布评论

评论列表(0)

  1. 暂无评论