How to use CDN Imports in a React-Project

一曲冷凌霜 提交于 2019-12-06 13:47:11

问题


My project is based on create-react-app and now I want to use Here Maps. Their documentation recommends loading the modules with CDN and I cant find any NPM packages for it. My question now is: how can I load the CDN properly?

I know there is the possibility to just put the CDN link inside my index.html file but this seems not to be the right solution I think.


回答1:


You can programmatically add JS script tags. Here's an example

function loadScript( {src, id, callback} ) {
  if(id && document.getElementById(id)){
    return; // don't accidentally re-add
  }
  const script = document.createElement( 'script' );
  if(callback){
    script.onload = callback;
  }
  if(id){
    script.setAttribute( 'id', id );
  }
  script.setAttribute( 'src', src );
  document.body.appendChild( script );
}

Usage example

componentDidMount(){
  loadScript({
    src: 'http://js.api.here.com/v3/3.0/mapsjs-core.js',
    id: 'script-mapsjs-core',
    callback: () => this.setState({mapsjsCoreLoaded: true})
  });
}



回答2:


After trying some things out, I found a solution for this use case. I installed this package "html-webpack-externals-plugin".

All you have to do is read the documentation for your use case. The "CDN-Use-Case" is also described.

For accessing the functions from the external JS-API you have to put a "window." in front of the function for example like this:

const map = new window.H.Map();

Hope this helps somebody!



来源:https://stackoverflow.com/questions/47495833/how-to-use-cdn-imports-in-a-react-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!