0

I am now trying to modulize my javascript code using RequireJS. I have 2 JS files (let's say A and B). A is a big file that has main code for my html page. B is a small utility library which is designed to be used by A and any other code in the future.

My plan is to firstly modulize B since B is small. After this I can write all my new code using RequireJS in the future and use B. On the other hand I will gradually modulize A. My concern now is that after I modulize B, is there a way that file A can continue use code in B so that my app can work correctly?

I cannot find out anything about this. Any suggestions, articles or sample code are welcome.

1 Answer 1

1

I just find out the answer myself. Actually it's very straight forward. just use RequireJS in your old code. For instance if I need to use JQuery in my old non-modulized code via RequireJS, I just need to:

first configure JQuery in the main.js

requirejs.config({
  baseUrl : '../js',
  paths : {
    'jquery' : 'jquery/jquery-1.10.2'
  },
  }
});

and add the main.js in the html

<script type="text/javascript" src="../js/require.js" data-main="../js/main.js"></script>

Then in the old code, use the function requirejs to ask the module (JQuery in this case) and invoke the module's functions.

  requirejs([ 'jquery' ],function(jquery)
  {
    jquery('#id').on('click',function(event){...});
  });

With this way, one can always gradually modulize code from a big, old and non-modulized JavaScript file step by step.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.