好的!下面给你整理一份 JavaScript 中 import 和 export 的用法总结,帮助你快速理解 ES6 模块化的核心概念和使用方法。


JavaScript 中 import 和 export 用法总结


一、export 的用法

export 用于在模块中导出变量、函数、类等,使它们可以被其他模块导入使用。

1. 命名导出(Named Export)

  • 可以导出多个变量或函数。
  • 导入时需要使用相同的名字。
// math.js
export const pi = 3.1415;
export function add(a, b) {
  return a + b;
}
export class Circle {
  constructor(radius) {
    this.radius = radius;
  }
}

或者统一导出:

const pi = 3.1415;
function add(a, b) { return a + b; }
class Circle { constructor(radius) { this.radius = radius; } }

export { pi, add, Circle };

2. 默认导出(Default Export)

  • 每个模块最多只能有一个默认导出。
  • 导入时可以自定义名字。
// utils.js
export default function greet(name) {
  return `Hello, ${name}!`;
}

二、import 的用法

1. 导入命名导出

  • 使用 {} 包裹需要导入的变量或函数名。
import { pi, add, Circle } from './math.js';

console.log(pi);           // 3.1415
console.log(add(2, 3));    // 5
const c = new Circle(10);

2. 导入默认导出

  • 可以自定义名字,且不用 {}
import greet from './utils.js';

console.log(greet('Alice'));  // Hello, Alice!

3. 导入命名导出并重命名

import { add as sum } from './math.js';

console.log(sum(1, 2));  // 3

4. 导入全部导出作为一个对象

import * as math from './math.js';

console.log(math.pi);
console.log(math.add(1, 2));

5. 只导入模块(不导入任何绑定),用于模块的副作用执行

import './setup.js';

三、综合示例

// helpers.js
export const name = 'Helper';
export function help() { console.log('Helping...'); }
export default function greet() { console.log('Hello!'); }
// app.js
import greet, { name, help } from './helpers.js';

console.log(name); // Helper
help();            // Helping...
greet();           // Hello!

四、小结

关键字说明备注
export导出变量、函数、类等命名导出或默认导出
export default默认导出每个模块只能有一个默认导出
import导入模块内容可导入命名导出或默认导出
{}用于导入命名导出必须与导出名字一致
* as导入所有导出作为一个对象方便统一管理多个导出

好的!下面帮你总结 CommonJS 和 ES6 模块化(require/module.exports vs import/export)的区别,并介绍 ES6 动态导入 import() 的用法和 Babel 相关配置。


一、CommonJS 与 ES6 模块的区别

特性CommonJS (require / module.exports)ES6 模块 (import / export)
规范类型运行时加载(同步)编译时静态分析(异步加载支持)
语法const mod = require('./mod')import mod from './mod.js'
导出方式module.exports = ... 或 exports.xxx = ...export default ... / export const ...
支持导入时重命名不支持,导入即是导出对象支持 { foo as bar }
支持动态导入通过调用 require() 实现原生支持 import() 动态导入
运行环境Node.js 默认支持浏览器和现代 Node.js 支持
模块加载方式同步加载(阻塞)静态声明,支持异步加载
循环依赖处理允许,部分加载可能为 undefined允许,绑定是动态的,访问时才取值

二、ES6 动态导入 import()

import() 是一个函数,返回一个 Promise,允许你按需异步加载模块。

语法示例

// 动态导入模块
import('./module.js')
  .then(module => {
    module.doSomething();
  })
  .catch(err => {
    console.error('加载失败', err);
  });

作用和优势

  • 支持条件加载和按需加载,提高页面性能。
  • 用于代码分割(code splitting),结合 Webpack 等打包工具使用。
  • 语法与静态 import 不同,更灵活。

三、Babel 编译 ES6 模块的相关配置

1. Babel 转换模块类型

  • Babel 默认将 ES6 import/export 转换成 CommonJS require/module.exports,适用于 Node.js 或不支持 ES6 模块的环境。

2. 配置示例(.babelrc

{
  "presets": [
    ["@babel/preset-env", {
      "modules": "commonjs"  // 转换成 CommonJS,默认值
    }]
  ]
}
  • 如果你想保持 ES6 模块不转换(例如配合 Webpack 做 Tree Shaking):
{
  "presets": [
    ["@babel/preset-env", {
      "modules": false
    }]
  ]
}

3. 支持动态导入

  • 需要安装插件支持:
npm install --save-dev @babel/plugin-syntax-dynamic-import
  • .babelrc 添加:
{
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}

四、总结

需求推荐方案
兼容 Node.js 环境CommonJS (require / module.exports)
现代浏览器或支持 ES6 模块ES6 import / export
按需异步加载模块ES6 动态导入 import()
Babel 编译"modules": false 保持 ES6 模块不转换
需要动态导入语法支持使用 @babel/plugin-syntax-dynamic-import

好的!下面给你一个示例项目结构和代码,演示如何在同一个项目中使用 CommonJS 和 ES6 模块,并用 Webpack + Babel 支持动态导入(import())和按需加载。


示例项目说明

  • 主入口用 ES6 模块
  • 同时加载 CommonJS 模块
  • 使用动态导入实现按需加载
  • 配置 Babel 转换 ES6,支持动态导入语法
  • 使用 Webpack 打包

1. 项目结构

demo-project/
│
├─ src/
│   ├─ index.js        # 主入口(ES6 模块)
│   ├─ utils.js        # ES6 模块
│   ├─ cjsModule.js    # CommonJS 模块
│   └─ dynamicModule.js # 动态加载模块(ES6)
│
├─ package.json
├─ webpack.config.js
└─ .babelrc

2. 代码示例

src/utils.js (ES6模块)

export function greet(name) {
  return `Hello, ${name}!`;
}

src/cjsModule.js (CommonJS模块)

function farewell(name) {
  return `Goodbye, ${name}!`;
}

module.exports = { farewell };

src/dynamicModule.js (动态导入的ES6模块)

export function dynamicFunc() {
  console.log('Dynamic module loaded!');
}

src/index.js (入口文件,ES6模块)

import { greet } from './utils.js';
const { farewell } = require('./cjsModule.js');

console.log(greet('Alice'));
console.log(farewell('Bob'));

// 动态导入
document.getElementById('loadBtn').addEventListener('click', () => {
  import('./dynamicModule.js').then(module => {
    module.dynamicFunc();
  }).catch(err => {
    console.error('加载动态模块失败', err);
  });
});

3. Webpack 配置(webpack.config.js)

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
    ],
  },
  devServer: {
    static: './dist',
    open: true,
  },
};

4. Babel 配置(.babelrc)

{
  "presets": [
    ["@babel/preset-env", {
      "modules": false
    }]
  ],
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}

5. package.json 依赖示例

{
  "name": "demo-project",
  "version": "1.0.0",
  "scripts": {
    "start": "webpack serve"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/preset-env": "^7.20.0",
    "babel-loader": "^9.1.2",
    "webpack": "^5.76.0",
    "webpack-cli": "^5.0.1",
    "webpack-dev-server": "^4.11.1"
  }
}

6. 运行步骤

npm install
npm run start

浏览器打开自动启动的页面,点击按钮测试动态模块加载。