49

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?

5
  • 1
    That's... not how importing in javascript works. You have to include the javascript in your HTML (using <script src.../>) and then you can import within your app using standard import methods. See this: stackoverflow.com/questions/34607252/es6-import-module-from-url Mar 20, 2017 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, 2017 at 23:06
  • 4
    @ShocKwav3_ Your question is valid. I think Tyler is not familiar with ES2015.
    – Chip Dean
    Mar 20, 2017 at 23:07
  • Possible duplicate of How to use a library from a CDN in a Webpack project in production
    – mastilver
    Jul 25, 2017 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'; Aug 22, 2018 at 8:31

5 Answers 5

30

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');
8
  • 29
    This is incorrect. She clearly says she is trying to import it into React.
    – Chip Dean
    Mar 20, 2017 at 23:06
  • 1
    He can import a local stylesheet file that contains the first example. Mar 20, 2017 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, 2017 at 23:08
  • Ah sorry. The pic is small :)
    – Chip Dean
    Mar 20, 2017 at 23:09
  • 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, 2019 at 17:23
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.

2
  • 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 9, 2021 at 15:21
  • 1
    The OP wants to pull the content from CDN url into the app bundle.
    – hazardous
    Oct 14, 2021 at 4: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

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);
}
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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.