Home > Enterprise >  Integrate JavaScript project to an existing ReactJS project
Integrate JavaScript project to an existing ReactJS project

Time:12-08

I want to integrate this repo to my existing react.js project https://github.com/zoltan-dulac/Matrix-Construction-Set . The Matrix-Construction-Set project has lots of Javascript files and some bower packages that are required to be present for it to work properly. I have installed bower and I have all packages under /bower_components that is at the same level as /node_modules. In the Matrix-Construction-Set project, all js files are included as <script/> after <body/> tag. I am using a custom hook that adds all those tags with src to the dom in the following way.

custom hook

import { useEffect } from 'react';

const useScript = url => {
    useEffect(() => {
        const script = document.createElement('script');

        script.src = url;
        script.async = true;

        document.body.appendChild(script);

        return () => {
            document.body.removeChild(script);
        }
    }, [url]);
};

export default useScript;

There are lots of js files that are included and below is just an example of how I do it inside a functional component. I have checked and all scripts are added to the dom.

useScript('../../../../assets/augmented3dmatrix/js/kmewhort/pointer_events_polyfill.js');
useScript('bower_components/visibleIf/shared/js/visibleIf.js');
useScript('bower_components/html5Forms/shared/js/EventHelpers.js');
useScript('bower_components/dialog-polyfill/dist/dialog-polyfill.js');
    

For now, I am getting errors of undefined in the visibleIf.js file.

src\assets\augmented3dmatrix\js\visibleIf.js
 Line 241:41:  'EventHelpers' is not defined      no-undef
  Line 488:41:  'url' is not defined               no-undef
  Line 488:47:  'config' is not defined            no-undef
  Line 492:76:  'url' is not defined               no-undef
  Line 576:31:  'ReadyState' is not defined        no-undef
  Line 580:31:  'HttpCode' is not defined          no-undef
  Line 580:60:  'HttpCode' is not defined          no-undef
  Line 672:18:  'j' is not defined                 no-undef

How do I add Bower packages so that the js file will have access to them?

IF someone knows a similar newer tool, please let me know.

CodePudding user response:

Try adding <script/> tags into the index.html file.

CodePudding user response:

I'd recommend to fork the repo and improve the code structure. If you have several functions you need, it's better to create an npm package. There are some instructions here on https://www.section.io/engineering-education/npm-packages/

  • Related