how to import libraries from cdn in reactjs?

前端 未结 3 1951
难免孤独
难免孤独 2020-12-28 14:22

I have tried:

import \'maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\';

but it produces error. How can i import a cdn in my

3条回答
  •  鱼传尺愫
    2020-12-28 14:32

    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

提交回复
热议问题