51

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 link into my app.js file?

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
ShocKwav3_
  • 1,670
  • 6
  • 22
  • 44
  • 1
    That's... not how importing in javascript works. You have to include the javascript in your HTML (using ``) and then you can import within your app using standard import methods. See this: http://stackoverflow.com/questions/34607252/es6-import-module-from-url – Tyler Sebastian Mar 20 '17 at 23:01
  • 4
    @TylerSebastian My apologies i'm quite new. I have, for example: `import './App.css';` this statement in my `app.js` file and i installed `bootsrap` with npm and was able to import bootstrap from my local directory and i was just thinking if there's any way to import from a cdn in `app.js` file. – ShocKwav3_ Mar 20 '17 at 23:06
  • 4
    @ShocKwav3_ Your question is valid. I think Tyler is not familiar with ES2015. – Chip Dean Mar 20 '17 at 23:07
  • Possible duplicate of [How to use a library from a CDN in a Webpack project in production](https://stackoverflow.com/questions/31575809/how-to-use-a-library-from-a-cdn-in-a-webpack-project-in-production) – mastilver Jul 25 '17 at 16:14
  • do not insert .CSS CDN links in your .JS files. Instead use `@import 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css';` inside your .css file ( assume it is App.css ), then import it into your App.js file using `import './App.css';` – Kavinda Prabhath Aug 22 '18 at 08:31

5 Answers5

32

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');
Lex
  • 4,749
  • 3
  • 45
  • 66
Rafael Berro
  • 2,518
  • 1
  • 17
  • 24
  • 30
    This is incorrect. She clearly says she is trying to import it into React. – Chip Dean Mar 20 '17 at 23:06
  • 1
    He can import a local stylesheet file that contains the first example. – Rafael Berro Mar 20 '17 at 23:07
  • yes i this is incorrect. i wanted to import it in my `app.js` file. @ChipDean thank you for mentioning that. ( i'm a 'he' btw :) ) – ShocKwav3_ Mar 20 '17 at 23:08
  • Ah sorry. The pic is small :) – Chip Dean Mar 20 '17 at 23:09
  • You can't do it that way, I have showed you some alternatives. – Rafael Berro Mar 20 '17 at 23:13
  • This should be the accepted answer. The plugin mentioned in the accepted answer does indirectly the same thing mentioned here. – Vishal Sharma Oct 22 '18 at 22:07
  • 2
    Even if you misinterpreted the question, this actually has solved my problem - I wanted to load a remote css file into my react app, without importing it. Thank you for your solution. – Rox Apr 18 '19 at 17:23
  • By the way, how can I load a cdn based js file inside my react project without importing the actual file? (without actually adding a script into the index.html) – Rox Apr 18 '19 at 17:25
15

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.

hazardous
  • 10,627
  • 2
  • 40
  • 52
  • Right, but you shouldn't have to bundle everything, that's the point. React bundles, which brings certain advantages, but it also brings limitations that would be nice to not have. – Cybernetic Oct 09 '21 at 15:21
  • 1
    The OP wants to pull the content from CDN url into the app bundle. – hazardous Oct 14 '21 at 04:50
6

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

CJY0208
  • 175
  • 2
  • 6
0

I don't know if it is applicable in this situation, but I use the following method to load CDN sources in case I need them. I use some libraries only if the corresponding element appears on the page:

const lazyLoadFromCDN = (callback: Function) => {
    const mathJax = document.createElement('script');
    mathJax.setAttribute('src', 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js');   
    mathJax.addEventListener('load', () => callback());
    document.head.appendChild(mathJax);
}
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Ozan
  • 1
  • 1
  • 5
0

I did something like this so you can

  1. wait for the script to load
  2. support for SSR
  3. will not attempt to load the script multiple times

Example:

const doSomething = async () => {
  const { isServer, loaded, ...event } = await loadScript('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js', {
    async: true 
  })
}

Source

import { pEvent } from 'p-event'

export const loadScript = async (src, opts = {}) => {
  if (typeof window === 'undefined') return { isServer: true }
  if (document.readyState === 'loading') {
    await pEvent(document, 'DOMContentLoaded')
  }
  const scriptEls = Array.from(document.getElementsByTagName('script'))
  const scripts = scriptEls.map(s => s.src)
  if (scripts.includes(src)) return { loaded: true }
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = src
  Object.assign(script, opts)
  let head = document.getElementsByTagName('head')[0]
  head.appendChild(script)
  const event = await pEvent(script, 'load')
  return event
}

Alex Cory
  • 10,635
  • 10
  • 52
  • 62