Add external javascript file to React.js app

删除回忆录丶 提交于 2021-02-11 14:48:00

问题


I'm having a little problem adding external javaScript file to my React App. I tried so many things but none of them worked. The last thing I did is:

step#1 : creating JS file and create functions.

step#2 : import the functions form my js file.

step#3 : call the functions.

The issue is when I run: npm start, everything work fine. But when I run: nom build, the script won't work!

This is my js file that I created with exporting functions

            export function BackgroundMove() {
            $(document).ready(function() {
                let movementStrength = 25;
                let height = movementStrength / $(window).height();
                let width = movementStrength / $(window).width();
                $("body").mousemove(function(e){
                        let pageX = e.pageX - ($(window).width() / 2);
                        let pageY = e.pageY - ($(window).height() / 2);
                        let newvalueX = width * pageX * -1 - 25;
                        let newvalueY = height * pageY * -1 - 50;
                        $('body').css("background-position", newvalueX+"px     "+newvalueY+"px");
                });
                });
            }


            export function HeaderMove() {
                $(document).ready(function(){
                    $('#nav-icon0,#nav-icon1,#nav-icon2,#nav-icon3,#nav-icon4').click(function(){
                        $(this).toggleClass('open');
                    });
                });
            }

Here I'm importing my functions

    import {HeaderMove, BackgroundMove} from '../../style';

Calling the functions:

   componentDidMount() {
      HeaderMove();
      BackgroundMove();
    }

As I mentioned, this will work fine when I run

 npm start 

But, when I run

npm build

my script won't work


回答1:


Please refer to the following code to import external javascript file inside component:

componentDidMount() {
   var script = document.createElement('script')
   script.src = // path of external javascript file.
   script.class = "external-script"
   document.body.appendChild(script);
}

and inside componentWillUnmount you can remove that file using the class name.



来源:https://stackoverflow.com/questions/53974071/add-external-javascript-file-to-react-js-app

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