I have 2 separate javascript files
#1.js
String.prototype.format = ....
String.prototype.capitalize = ....
#2.js
//................
var text = "some text{0}".format(var1)
//................
How do I make string#format
and string#capitalize
available in the second file?
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.
To import a variable from another file in JavaScript:Export the variable from file A , e.g. export const str = 'Hello world' . Import the variable in file B as import { str } from './another-file.
It is not possible to load multiple javascript files in a single <script> element. You have to have to have an individual <script> element for each script you are referencing..
JavaScript executes globally. Adding both scripts on the page makes them available to each other as if they were in one file.
<script src="1.js"></script> <script src="2.js"></script>
However, you should note that JavaScript is parsed "linearly" and thus, "first parsed, first served". If the first script needs something in the second script, but the second script hasn't been parsed yet, it will result in an error.
If that happens, you should rethink your script structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With