how to import libraries from cdn in reactjs?

You can include these lines within your html file:

<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

Or, you can import a local stylesheet file that contains the import instruction. See the example below:

App.js

import './App.scss';

App.scss

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

You don't bundle CDN stuff inside your JS, that sort of defeats the purpose of having it on CDN :). Had this been JS, I would have asked you to use externals, but for a CSS, you can use https://github.com/jso0/html-webpack-cdn-plugin instead.


I think we can write some function like this

const fetchJsFromCDN = (src, externals = []) => {
  new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.setAttribute('src', src)
    script.addEventListener('load', () => {
      resolve(externals.map(key => {
        const ext = window[key]
        typeof ext === 'undefined' && console.warn(`No external named '${key}' in window`)
        return ext
      }))
    })
    script.addEventListener('error', reject)
    document.body.appendChild(script)
  })
}

fetchJsFromCDN('//cdn.jsdelivr.net/npm/eruda', ['eruda']).then(([eruda]) => eruda.init())

without function like require, CDN source may inject object to window so we can get it by given name

CSS files could be easier to import with this way

Tags:

Reactjs