How to import libraries from cdn to reactjs?

I tried:

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

but it causes an error. How can I import cdn into my app.js file?

+12
reactjs
source share
3 answers

You do not bind a CDN inside your JS, it defeats the goal of having it in a CDN :). If it were JS, I would ask you to use external components , but for CSS you can use https://github.com/jso0/html-webpack-cdn-plugin .

+5
source share

You can include these lines in 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 an import statement. See an example below:

App.js

 import './App.scss'; 

App.scss

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

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 a function like require , the CDN source can insert an object into the window so that we can get it using the name

CSS files may be easier to import this way

+2
source share

All Articles