阿里云主机折上折
  • 微信号
Current Site:Index > Basic export syntax for exporting statements

Basic export syntax for exporting statements

Author:Chuan Chen 阅读数:1259人阅读 分类: JavaScript

Overview of Basic Export Syntax

In the ECMAScript 6 module system, the export keyword is used to export functions, objects, or primitive values from a module, making them available for other modules to use via import statements. The basic export syntax includes two main forms: named exports and default exports.

Named Exports

Named exports allow a module to export multiple values, each with a name. The same names must be used when importing.

// Export individual declarations
export const name = 'Zhang San';
export function sayHello() {
  console.log('Hello!');
}
export class Person {
  constructor(name) {
    this.name = name;
  }
}

// Export list
const age = 25;
function multiply(a, b) {
  return a * b;
}
export { age, multiply };

// Rename exports
export { age as userAge, multiply as product };

Features of named exports:

  1. Can be exported directly at declaration
  2. Can be declared first and then exported collectively
  3. Supports renaming with the as keyword

Default Exports

Each module can have one default export, which can be imported using any name.

// Direct default export
export default function() {
  console.log('This is a default export');
}

// Define first, then default export
const myObject = {
  name: 'Default Object',
  version: 1.0
};
export default myObject;

// Default export a class
export default class Logger {
  log(message) {
    console.log(message);
  }
}

Features of default exports:

  1. A module can have only one default export
  2. Can be imported with a custom name
  3. Does not use curly braces when exporting

Mixed Exports

A module can contain both named exports and a default export.

// Default export
export default class User {
  constructor(name) {
    this.name = name;
  }
}

// Named exports
export const MAX_USERS = 100;
export function validateUser(user) {
  return user.name.length > 0;
}

Re-exporting

Modules can re-export exports from other modules, often used to create aggregated modules.

// Re-export all named exports from another module
export * from './math.js';

// Selective re-export
export { PI, sqrt } from './math.js';

// Rename and re-export
export { encrypt as secureEncrypt } from './crypto.js';

// Re-export default export
export { default } from './logger.js';

Dynamic Binding of Exported Values

ES6 modules export dynamic bindings, not copies of values. When a value changes inside the module, the imported value updates accordingly.

// counter.js
export let count = 0;
export function increment() {
  count++;
}

// main.js
import { count, increment } from './counter.js';
console.log(count); // 0
increment();
console.log(count); // 1

Exports and Hoisting

export statements are affected by JavaScript hoisting, but the best practice is to explicitly list all exports at the top of the module.

// Works but not recommended
sayHello(); // Works fine
export function sayHello() {
  console.log('Hello');
}

// Recommended
export function sayHello() {
  console.log('Hello');
}
sayHello();

Common Export Patterns

Common export patterns in real-world development:

  1. Utility library export pattern
// utils.js
export function formatDate(date) { /*...*/ }
export function truncate(text, length) { /*...*/ }
export function debounce(fn, delay) { /*...*/ }
  1. Configuration object export pattern
// config.js
export default {
  apiUrl: 'https://api.example.com',
  timeout: 5000,
  retries: 3
};
  1. Class and helper function combination export
// validator.js
export default class Validator {
  // Class implementation
}

export function validateEmail(email) {
  // Helper function
}

export function validatePassword(password) {
  // Helper function
}

Exports and Module Identifiers

Exported identifiers must follow JavaScript variable naming rules and cannot use reserved words as names.

// Valid export
export const $ = jQuery;
export function class() {} // Syntax error

// Solution
export function klass() {} // Rename
export { class as Class }; // Use 'as' to rename

Immutability of Exported Values

In strict mode, exported variables are read-only and cannot be directly modified.

// constants.js
export const VERSION = '1.0.0';

// app.js
import { VERSION } from './constants.js';
VERSION = '2.0.0'; // TypeError: Assignment to constant variable

Exports in Circular Dependencies

The ES6 module system supports circular dependencies, but initialization order must be considered.

// a.js
import { b } from './b.js';
export const a = 'a' + b;

// b.js
import { a } from './a.js';
export const b = 'b' + a;

Exports and Live Bindings

Exported bindings are live, meaning if a module modifies an exported value, all imports of that value will see the update.

// counter.js
export let value = 0;
export function increment() {
  value++;
}

// app.js
import { value, increment } from './counter.js';
console.log(value); // 0
increment();
console.log(value); // 1

Common Export Syntax Errors

Understanding common export errors helps avoid issues.

// Error 1: Exporting undeclared value
export x; // SyntaxError

// Error 2: Default export followed by declaration
export default const x = 1; // SyntaxError

// Error 3: Duplicate default export
export default function() {}
export default class {} // SyntaxError

// Error 4: Exporting undefined variable
const y = 1;
export { x }; // ReferenceError

Exports and Static Module Analysis

ES6 module exports are static, meaning they must be at the top level of the module and cannot be inside conditionals or functions.

// Incorrect example
if (condition) {
  export const x = 1; // SyntaxError
}

function exportSomething() {
  export const y = 2; // SyntaxError
}

Differences Between Exports and CommonJS

Key differences between ES6 exports and CommonJS module.exports:

  1. ES6 exports are static; CommonJS exports are dynamic
  2. ES6 exports bindings; CommonJS exports copies of values
  3. ES6 supports named and default exports; CommonJS has only one export method
// CommonJS export
module.exports = {
  name: 'CommonJS',
  version: 1
};

// Equivalent ES6 export
export default {
  name: 'ES6',
  version: 6
};

Exports and Tree Shaking

Good export practices help bundlers perform Tree Shaking optimizations to remove unused code.

// Recommended: Export utility functions separately
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }

// Not recommended: Export entire object
export default {
  add(a, b) { return a + b; },
  subtract(a, b) { return a - b; }
};

Exports and Module Encapsulation

Proper use of exports enables module encapsulation and information hiding.

// privateCounter.js
let count = 0; // Private variable

export function increment() {
  count++;
}

export function getCount() {
  return count;
}

// External code cannot directly access 'count'

Exports and TypeScript

When using ES6 exports in TypeScript, type annotations can be added.

// types.ts
export interface User {
  id: number;
  name: string;
}

export type Status = 'active' | 'inactive';

// Default export class
export default class AuthService {
  login(user: User): Promise<boolean> {
    // Implementation
  }
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.