Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to import JavaScript files into one file?

Tags:

javascript

oop

I have a background in coding in languages that have a concept of "classes". Now that I am coding JavaScript, I would like to code in a similar way so that each object oriented "class" I create is its own separate file.

  • see Accessing "Public" methods from "Private" methods in javascript class

  • see http://phrogz.net/JS/classes/OOPinJS.html

In other languages, I would create import statements at the top of the class file to ensure other custom classes that were used within a class file so that the other custom classes were compiled into the final binary.

Of course JavaScript is not a compiled language; however, I would still like to be able to be include some kind of "import" statement at the top of custom class files so I could ensure the imported JS "class" file was available for the user's browser to download.

It would be ideal if there were a 3rd party tool that combined all of my separate class files into one JS file so the browser only had to make one HTTP request for a single JS file instead of many calls for each indicidual JS "class". Does anyone know if such a tool exists where it would do the following:

  1. allowed me to choose which JS files that I wanted to include in a single JS file
  2. crawled thru the files I selected in step 1 and found all the "import" statements at the top of each custom "class" file. These "import" statements could simply be specially formatted comments in the code that the 3rd party recognizes as import statements.
  3. The 3rd party would then create the single JS file with all of the files that were selected from step 1 and from all of the imported files that were found in step 2.

Some popular JavaScript frameworks seem to do just that. For example, jQueryUI allows you to customize the download of a single jQueryUI source file by allowing the user to check off which objects you want to use. If you uncheck an element that is needed for an item that you checked off, then the form tells you that there is a dependency you need to rectify before being able to proceed to download the file.

  • see http://jqueryui.com/download/

So is there a 3rd party tool that allows a developer to use some kind of "import" statement comment to ensure that many dependent JS files (and only the ones that the developer needs) to be combined into a single JS file?

like image 296
jaxim Avatar asked Feb 18 '23 17:02

jaxim


2 Answers

RequireJS was built for exactly this purpose.

like image 120
Wayne Koorts Avatar answered Feb 20 '23 09:02

Wayne Koorts


Have a look at Require.js. It lets you import various javascript files in a modularized fashion and add the required dependencies between them. Also at the end you can minify them all into one single JS file using r.js

like image 42
Reza S Avatar answered Feb 20 '23 08:02

Reza S