ES6 (ECMAScript 2015) introduced a standardized module system to JavaScript, revolutionizing how we organize and share code. In this article, we'll explore the ins and outs of ES6 imports, providing real-world examples and a demo project to illustrate their power and flexibility.
The basic syntax for importing in ES6 is:
import { something } from './module-file.js';
This imports a named export called something from the file module-file.js in the same directory.
Named exports allow you to export multiple values from a module:
// math.js export const add = (a, b) => a b; export const subtract = (a, b) => a - b; // main.js import { add, subtract } from './math.js'; console.log(add(5, 3)); // Output: 8 console.log(subtract(10, 4)); // Output: 6
Default exports provide a main exported value for a module:
// greet.js export default function greet(name) { return `Hello, ${name}!`; } // main.js import greet from './greet.js'; console.log(greet('Alice')); // Output: Hello, Alice!
You can combine named and default exports in a single module:
// utils.js export const VERSION = '1.0.0'; export function helper() { /* ... */ } export default class MainUtil { /* ... */ } // main.js import MainUtil, { VERSION, helper } from './utils.js'; console.log(VERSION); // Output: 1.0.0 const util = new MainUtil(); helper();
You can rename imports to avoid naming conflicts:
// module.js export const someFunction = () => { /* ... */ }; // main.js import { someFunction as myFunction } from './module.js'; myFunction();
You can import all exports from a module as a single object:
// module.js export const a = 1; export const b = 2; export function c() { /* ... */ } // main.js import * as myModule from './module.js'; console.log(myModule.a); // Output: 1 console.log(myModule.b); // Output: 2 myModule.c();
Dynamic imports allow you to load modules on demand:
async function loadModule() { const module = await import('./dynamicModule.js'); module.doSomething(); } loadModule();
// Button.js import React from 'react'; export default function Button({ text, onClick }) { return ; } // App.js import React from 'react'; import Button from './Button'; function App() { return
// database.js import mongoose from 'mongoose'; export async function connect() { await mongoose.connect('mongodb://localhost:27017/myapp'); } // server.js import express from 'express'; import { connect } from './database.js'; const app = express(); connect().then(() => { app.listen(3000, () => console.log('Server running')); });
Let's create a simple task manager to demonstrate ES6 imports in action:
// task.js export class Task { constructor(id, title, completed = false) { this.id = id; this.title = title; this.completed = completed; } toggle() { this.completed = !this.completed; } } // taskManager.js import { Task } from './task.js'; export class TaskManager { constructor() { this.tasks = []; } addTask(title) { const id = this.tasks.length 1; const task = new Task(id, title); this.tasks.push(task); return task; } toggleTask(id) { const task = this.tasks.find(t => t.id === id); if (task) { task.toggle(); } } getTasks() { return this.tasks; } } // app.js import { TaskManager } from './taskManager.js'; const manager = new TaskManager(); manager.addTask('Learn ES6 imports'); manager.addTask('Build a demo project'); console.log(manager.getTasks()); manager.toggleTask(1); console.log(manager.getTasks());
To run this demo, you'll need to use a JavaScript environment that supports ES6 modules, such as Node.js with the --experimental-modules flag or a modern browser with a bundler like webpack or Rollup.
ES6 imports provide a powerful and flexible way to organize JavaScript code. By understanding the various import and export syntaxes, you can create more modular, maintainable, and efficient applications. The demo project and real-world examples provided here should give you a solid foundation for using ES6 imports in your own projects.
Remember to always consider the specific needs of your project when deciding how to structure your modules and imports. Happy coding!
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3