Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import/include source files in JavaScript? [duplicate]

Possible Duplicate:
How to include js file in another js file?

Suppose I have a few JavaScript source files: a.js, a1.js, and a2.js. Functions of a.js invoke functions from a1.js and a2.js.

Now I have to declare all these files in my HTML page. I would like to declare only a.js in the HTML and "import/include" a1.js, and a2.js in the a.js source file.

Does it make sense? Can I do that in JavaScript?

like image 263
Michael Avatar asked Jun 28 '12 16:06

Michael


People also ask

How do I link two JavaScript files?

Answer: Use the export and import Statement Since ECMAScript 6 (or ES6) you can use the export or import statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.

Can one JavaScript file reference another?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.


1 Answers

You can't specify imports in vanilla javascript.

So your solutions (excluding heavy server side frameworks) are :

  • simply do the imports

  • concatenate your js files (and minify them in the same move, for exemple using the closure compiler)

  • use a module itool like require.js

As long as you're not experienced, and if your number of files is low (less than 15), I recommend to simply choose the first or second solution. Using a module loader may have side effects you don't want to debug when beginning to learn javascript.

like image 100
Denys Séguret Avatar answered Oct 27 '22 11:10

Denys Séguret