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

前端 未结 4 480
北恋
北恋 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 22:13

    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(`
        
        
          
            
            ${styles}
            ${title}
          
          
            
    ${ssrHTML}
    `); ~~~

提交回复
热议问题