The eval function evaluates JavaScript code represented as a string.Įvaluating the JavaScript code means it runs the code which was passed to the function in a string. Then we are accessing the code of the JavaScript file using the text function and stored it in utilsText then passed it to the eval function. We are waiting for our HTML page to load and then fetching the utils file using fetch. Let's rewrite the earlier greet example using require in Node JS.Ĭreate a new file utils.js with the following code: Node JS has the module system even before the introduction of ES6 modules in JavaScript. ![]() You need to install Node JS to run the code given in this section. Node.js is an open-source, cross-platform, backend JavaScript runtime environment used to execute JavaScript code outside a web browser. You may skip this section if you are new to JavaScript.Īnother popular way to import and export JS files is using the Node JS require function. The following section requires a basic understanding of Node JS Framework. If you are using VS Code, you can use the live server extension to host the HTML file. ![]() You can't load the modules locally (that is with a file:// URL) inside your browsers due to JavaScript module security requirements. Open the HTML file in a browser using a local server and then open the console (press F12). The type="module" allows the use of import and export inside a JS file. We need the type="module" attribute in the element to declare this script as a module. Create a file named utils.js and define the following function and constant inside it: Let's start by using the ES6 way of importing and exporting. In this section, we will learn about two popular ways of including a JS file in another JS file: Popular Ways to Include a JavaScript File in Another JavaScript File Let's discuss different ways to achieve modularity and learn how to import a JS file into a JS file.Īn ES6 module is a JS file that can export its code to share with other files and import and use code from other JS files.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |