Rust高性能JavaScript打包工具swc_node_bundler的使用,支持快速模块打包和代码优化

cargo add swc_node_bundler

swc_node_bundler = “36.0.0”

use swc_node_bundler::{Bundler, Config};
use std::path::PathBuf;

fn main() {
    // 创建配置对象
    let config = Config {
        // 入口文件路径
        entry: PathBuf::from("src/main.js"),
        // 输出文件路径
        output: PathBuf::from("dist/bundle.js"),
        // 启用代码优化
        minify: true,
        // 启用source map生成
        source_map: true,
        // 其他配置选项...
    };

    // 创建打包器实例
    let mut bundler = Bundler::new(config);
    
    // 执行打包操作
    match bundler.bundle() {
        Ok(_) => println!("打包成功完成!"),
        Err(e) => eprintln!("打包失败: {}", e),
    }
}
// src/main.js
import { add } from './math.js';
import { greet } from './utils.js';

console.log(greet('World'));
console.log('2 + 3 =', add(2, 3));

// src/math.js
export function add(a, b) {
    return a + b;
}

export function subtract(a, b) {
    return a - b;
}

// src/utils.js
export function greet(name) {
    return `Hello, ${name}!`;
}
// 完整示例:使用swc_node_bundler进行高级配置
use swc_node_bundler::{Bundler, Config, OptimizationLevel};
use std::path::PathBuf;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 详细配置选项
    let config = Config {
        entry: PathBuf::from("src/main.js"),
        output: PathBuf::from("dist/bundle.min.js"),
        minify: true,
        source_map: true,
        target: Some("es2015".to_string()), // 目标ES版本
        optimization: OptimizationLevel::High, // 优化级别
        exclude: vec!["node_modules".to_string()], // 排除目录
        include: vec!["src/**/*.js".to_string()], // 包含模式
        // 更多配置选项...
    };

    // 初始化打包器
    let mut bundler = Bundler::new(config);
    
    // 添加自定义插件或转换器
    // bundler.add_plugin(...);
    
    // 执行打包过程
    bundler.bundle()?;
    
    println!("JavaScript模块打包和优化完成!");
    Ok(())
}
# Cargo.toml 依赖配置
[package]
name = "my-bundler"
version = "0.1.0"
edition = "2021"

[dependencies]
swc_node_bundler = "36.0.0"
swc_core = { version = "0.86.0", features = ["bundler"] }
# 运行打包命令
cargo run

# 或者直接使用swc_cli(如果安装)
# npx swc-bundle src/main.js -o dist/bundle.js --minify

1 回复

Rust高性能JavaScript打包工具:swc_node_bundler

工具简介

swc_node_bundler是一个基于Rust和SWC(Speedy Web Compiler)构建的高性能JavaScript/TypeScript模块打包工具。它专为现代前端开发设计,提供极快的打包速度和先进的代码优化能力,特别适合大型项目构建。

主要特性

  • ⚡ 基于Rust和SWC,打包速度比传统工具快5-20倍
  • 📦 支持ES Modules和CommonJS模块系统
  • 🔧 内置TypeScript编译支持
  • 🎯 智能tree-shaking和代码分割
  • 🔍 源码映射(Source Maps)生成
  • 🛠️ 丰富的插件生态系统

安装方法

# 使用npm安装
npm install -g swc_node_bundler

# 或者使用yarn
yarn global add swc_node_bundler

# 作为项目依赖安装
npm install --save-dev swc_node_bundler

基本使用方法

命令行使用

# 打包单个入口文件
swc-bundle ./src/index.js -o ./dist/bundle.js

# 打包并启用压缩优化
swc-bundle ./src/index.js -o ./dist/bundle.min.js --minify

# 打包TypeScript项目
swc-bundle ./src/index.ts -o ./dist/bundle.js

# 监听文件变化并自动重新打包
swc-bundle ./src/index.js -o ./dist/bundle.js --watch

配置文件使用

创建 swc.config.js 文件:

// swc.config.js
module.exports = {
  entry: './src/index.js',
  output: {
    path: './dist',
    filename: 'bundle.js'
  },
  mode: 'production', // 'development' 或 'production'
  minify: true,
  sourceMap: true,
  target: 'es2015', // 支持es5, es2015, es2016, es2017, es2018, es2019, es2020
  external: ['react', 'react-dom'] // 外部依赖排除
};

然后运行:

swc-bundle --config swc.config.js

示例项目结构

project/
├── src/
│   ├── index.js
│   ├── utils.js
│   └── components/
│       └── button.js
├── package.json
└── swc.config.js

示例代码

// src/utils.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;

// src/components/button.js
export const createButton = (text) => {
  const button = document.createElement('button');
  button.textContent = text;
  return button;
};

// src/index.js
import { add } from './utils.js';
import { createButton } from './components/button.js';

console.log(add(2, 3));
document.body.appendChild(createButton('Click me'));

高级配置选项

// 高级配置示例
module.exports = {
  entry: {
    main: './src/index.js',
    vendor: './src/vendor.js'
  },
  output: {
    path: './dist',
    filename: '[name].[hash].js',
    chunkFilename: '[name].[chunkhash].js'
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  },
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx']
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'swc-loader',
        exclude: /node_modules/
      }
    ]
  }
};

性能对比

与webpack的对比测试显示:

  • 冷启动时间减少约70%
  • 增量构建速度提升约5倍
  • 内存使用量减少约60%
  • 最终打包体积相当或更优

注意事项

  1. 确保Node.js版本 >= 12.0.0
  2. 对于大型项目,建议使用配置文件而非命令行参数
  3. 某些webpack特有的功能可能需要额外插件支持
  4. 生产环境构建时务必启用minify选项以获得最佳性能

这个工具特别适合对构建性能有严格要求的大型项目,能够显著提升开发体验和CI/CD流水线效率。

完整示例demo

基于上述示例代码,以下是一个完整的项目demo:

项目结构:

swc-demo-project/
├── src/
│   ├── index.js
│   ├── utils.js
│   └── components/
│       └── button.js
├── package.json
├── swc.config.js
└── index.html

package.json:

{
  "name": "swc-demo-project",
  "version": "1.0.0",
  "description": "SWC打包工具演示项目",
  "main": "dist/bundle.js",
  "scripts": {
    "build": "swc-bundle --config swc.config.js",
    "dev": "swc-bundle --config swc.config.js --watch"
  },
  "devDependencies": {
    "swc_node_bundler": "^1.0.0"
  }
}

swc.config.js:

// SWC打包配置文件
module.exports = {
  entry: './src/index.js',
  output: {
    path: './dist',
    filename: 'bundle.js'
  },
  mode: 'development',
  minify: false,
  sourceMap: true,
  target: 'es2015'
};

src/utils.js:

// 工具函数模块
/**
 * 加法函数
 * @param {number} a - 第一个数字
 * @param {number} b - 第二个数字
 * @returns {number} 两数之和
 */
export const add = (a, b) => a + b;

/**
 * 乘法函数
 * @param {number} a - 第一个数字
 * @param {number} b - 第二个数字
 * @returns {number} 两数之积
 */
export const multiply = (a, b) => a * b;

src/components/button.js:

// 按钮组件模块
/**
 * 创建按钮元素
 * @param {string} text - 按钮文本
 * @returns {HTMLButtonElement} 创建的按钮元素
 */
export const createButton = (text) => {
  const button = document.createElement('button');
  button.textContent = text;
  button.style.padding = '10px 20px';
  button.style.margin = '10px';
  button.style.backgroundColor = '#007bff';
  button.style.color = 'white';
  button.style.border = 'none';
  button.style.borderRadius = '5px';
  button.style.cursor = 'pointer';
  
  // 添加点击事件
  button.addEventListener('click', () => {
    console.log('按钮被点击:', text);
  });
  
  return button;
};

src/index.js:

// 项目入口文件
import { add } from './utils.js';
import { createButton } from './components/button.js';

// 使用工具函数
console.log('加法结果:', add(2, 3));
console.log('加法结果:', add(5, 7));

// 创建并添加按钮到页面
document.body.appendChild(createButton('第一个按钮'));
document.body.appendChild(createButton('第二个按钮'));
document.body.appendChild(createButton('第三个按钮'));

// 添加页面样式
const style = document.createElement('style');
style.textContent = `
  body {
    font-family: Arial, sans-serif;
    padding: 20px;
    background-color: #f0f0f0;
  }
`;
document.head.appendChild(style);

console.log('SWC打包演示项目运行成功!');

index.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SWC打包工具演示</title>
</head>
<body>
    <h1>SWC打包工具演示页面</h1>
    <p>打开浏览器控制台查看输出结果</p>
    
    <!-- 打包后的JS文件 -->
    <script src="./dist/bundle.js"></script>
</body>
</html>

使用步骤:

  1. 创建项目目录并初始化:
mkdir swc-demo-project
cd swc-demo-project
npm init -y
  1. 安装swc_node_bundler:
npm install --save-dev swc_node_bundler
  1. 创建上述所有文件

  2. 运行打包命令:

npm run build
  1. 在浏览器中打开index.html查看效果

这个完整的demo展示了swc_node_bundler的基本使用方法,包括模块导入导出、组件创建、样式处理等功能。打包后的bundle.js文件包含了所有模块的代码,可以直接在浏览器中运行。

回到顶部