By the end of this lesson, you will be able to run modules through a local development server. This skill is vital for building and testing real applications effectively.
To create reliable applications, it is crucial to run modules through a local development server. For example, consider a web app that shows weather information. Running this app in a local environment allows you to see live changes instantly. A local server creates a safe space for testing and debugging your code. This is beneficial for beginners and students alike.
There are various methods to run JavaScript modules on a local server. First, you can use built-in tools from platforms such as Node.js. Alternatively, you can install software like XAMPP or WAMP. Next, choose the method that works for you. Follow the necessary installation steps. Then, navigate your terminal or command prompt to the folder of your project.
File: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Module Example</title>
</head>
<body>
<script type="module" src="main.js"></script>
</body>
</html>
// main.js
import { greet } from './greet.js';
greet();
// greet.js
export function greet() {
console.log('Hello, World!');
}
Hello, World!
In the code above, the index.html file includes main.js as a module using type="module". The main.js file imports the greet function from greet.js and runs it. The function then prints “Hello, World!” to the console. This demonstration shows you how to efficiently run modules through a local development server.
Create a new JavaScript module that exports a function, which returns your favorite food. Next, import this module into your main JavaScript file. This task will help reinforce the concept of using modules effectively.
File: favoriteFood.js
export function favoriteFood() {
return 'Pizza';
}
File: main.js
import { favoriteFood } from './favoriteFood.js';
console.log(favoriteFood());
Pizza
type="module" in the HTML file. This is essential for proper module loading.type="module" attribute in your script tag.