简体   繁体   中英

Add external javascript file to React.js app

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM