Introduction to Modules
Modules are a way to organize code into separate files, making it easier to maintain and reuse. They help in creating a clear structure for projects of any size.
ES6 Modules
ES6 introduced a standardized module format to JavaScript.
Exporting
You can export functions, objects, or primitive values from a module:
// math.js
export function add(x, y) {
return x + y;
}
export function subtract(x, y) {
return x - y;
}
export const PI = 3.14159;
You can also use a default export:
// person.js
export default class Person {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
}
Importing
To use the exported items in another file:
// main.js
import { add, subtract, PI } from './math.js';
import Person from './person.js';
console.log(add(5, 3)); // Outputs: 8
console.log(PI); // Outputs: 3.14159
const john = new Person('John');
john.sayHello(); // Outputs: Hello, my name is John
Using Modules in the Browser
To use ES6 modules in the browser, you need to specify the type as “module” in the script tag:
<script type="module" src="main.js"></script>
Introduction to Build Tools
Build tools automate the process of preparing JavaScript code for production. They can handle tasks like bundling, minification, and transpilation.
Webpack
Webpack is a popular module bundler. It takes modules with dependencies and generates static assets representing those modules.
Basic Webpack Configuration
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};
Babel
Babel is a JavaScript compiler that allows you to use next generation JavaScript, today.
Basic Babel Configuration
// .babelrc
{
"presets": ["@babel/preset-env"]
}
NPM Scripts
NPM scripts provide a way to run command-line tools installed with npm.
// package.json
{
"scripts": {
"build": "webpack --mode production",
"start": "webpack serve --open --mode development"
}
}
Practical Example: Modular Weather App
Let’s refactor our weather app from the previous lesson to use modules and a basic build setup:
// api.js
const API_KEY = 'YOUR_API_KEY';
export async function getWeather(city) {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`);
if (!response.ok) {
throw new Error('City not found');
}
return response.json();
}
// ui.js
export function updateUI(weatherData) {
const weatherResult = document.getElementById('weatherResult');
weatherResult.textContent = `Temperature in ${weatherData.name}: ${weatherData.main.temp}°C`;
}
// index.js
import { getWeather } from './api.js';
import { updateUI } from './ui.js';
document.getElementById('getWeather').addEventListener('click', async () => {
const city = document.getElementById('cityInput').value;
try {
const data = await getWeather(city);
updateUI(data);
} catch (error) {
document.getElementById('weatherResult').textContent = `Error: ${error.message}`;
}
});
To use this with Webpack, you’d need to install necessary dependencies and set up a webpack.config.js
file.
Practice Exercise
- Set up a new project using npm and initialize it with
package.json
. - Install Webpack and Babel as dev dependencies.
- Create a Webpack configuration file to bundle your JavaScript modules.
- Add npm scripts to build and serve your project.
- Extend the weather app to include a 5-day forecast, organizing the new functionality into appropriate modules.
Conclusion
This lesson introduced JavaScript modules and basic build tools. These concepts are crucial for organizing and optimizing larger JavaScript projects. Modules help in creating maintainable and reusable code, while build tools like Webpack and Babel enable you to use modern JavaScript features and optimize your code for production.
In the next lesson, we’ll explore more advanced JavaScript patterns and best practices for writing clean, efficient code.
Remember to practice these concepts by refactoring existing projects to use modules and setting up your own build processes!