Thursday, November 10, 2016

Module and require(...)



When your code begins to get larger and larger, it is sometimes interesting to split it in several files. However, there is no import or include by default in JavaScript. Here is a simple way to implement such a function...

Thanks to Marijn Haverbeke in his book 'Eloquent JavaScript', we can define a simple require() function allowing to load source files located in the hard disk. This implementation is based on the Module design pattern and on the object Function.

1. Module and function require()



++++ JavaScript: require.js ++++ ++++ End of JavaScript: require.js ++++



2. Example with the chessboard

How can we use this require(...) function? In a previous implementation of our 'Drawing a Chessboard' series [Link], the code is made of two parts: (i) the definition of  a class Cell and (ii) the main body of the script. If I want to reuse the class Cell somewhere else, I have to copy and paste the lines of code in a new script... that's not really convenient. Thus,  rather than having all the code in a single file, I split the code in two files:

  1. A file entitled chessboard_cell.js contains the code of the class Cell. (lines 7-28)
  2.  chessboard.js contains the main part of the script. (lines 30-53)

Then, modify the chessboard_cell.js by adding at the end of the code, the expression:
exports.Cell = Cell;
Now, load your chessboard.js in ImageJ (File > Open...), then add the definition of the function require(...) at the end of the code...

and modify the code by adding at the beginning, the file(s) required for your script. Here I need the chessboard_cell.js and import this file by typing...
var chess = require('chessboard_cell.js');
Thus, we define the module chess containing the class Cell. If you want to create a new object Cell (instance of...), you have to type ...

var myCell = new chess.Cell(x,y,size);


Here is the final code.

++++ JavaScript: chessboard.js ++++ ++++ End of JavaScript: chessboard.js ++++

No comments:

Post a Comment