Is there a way to use cdn files with reactjs using webpack?

后端 未结 2 2000
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 06:39

I am not able to configure pusher and fetch using npm in reactjs.Also,is there any way to use cdn inside your react code?

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-09 07:00

    You can use the react-async-script-loader as a Higher Order Component for this: https://github.com/leozdgao/react-async-script-loader

    Just install it via npm:

    npm install --save react-async-script-loader
    

    then Import it and extend your component that needs the cdn javascripts with the scriptLoader giving it the urls you would like to include for your component.

    import scriptLoader from 'react-async-script-loader';
    
    // Your component code:
    class YourComponent extends React.Component {
      render() {
        return 

    { this.props.isScriptLoadSucceed ? 'Scripts loaded.' : 'Loading...' }

    ; } } export default scriptLoader([ 'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.min.js' ])(YourComponent);

    This way the files are only loaded where you really need them. Once loaded, they do not get included again (if you update the component).

    Decorator (ES7) syntax works as well if you like it more than a HOC implementation, this is documented in the projects README.

提交回复
热议问题