引言
大家好,欢迎来到第2期的JavaScript库推荐!本期为大家介绍的是 Rsbuild,一个基于 Rspack 的高性能 Web 构建工具,提供开箱即用的构建配置和卓越的开发体验。
在现代前端开发中,我们经常遇到构建速度慢、配置复杂、开发体验差等痛点。传统的构建工具如 Webpack 虽然功能强大,但往往存在配置繁琐、构建速度慢、学习成本高等问题。Rsbuild 正是为了解决这些痛点而生的,它以其开箱即用的配置、5-10倍的构建性能提升、优秀的生态兼容性在构建工具中脱颖而出,成为了现代前端项目的首选构建方案。
本文将从 Rsbuild 的核心特性、实际应用、性能表现、最佳实践等多个维度进行深入分析,帮助你全面了解这个优秀的构建工具。
库介绍
基本信息
- 库名称:Rsbuild
- GitHub地址 :github.com/web-infra-d...
- npm地址 :www.npmjs.com/package/@rs...
- 官方文档 :rsbuild.dev/zh/
- GitHub Stars:9.8k+ ⭐
- 最新版本:v1.x
- 包大小:轻量级依赖体积
- 维护状态:活跃维护中
主要特性
- 🚀 极致性能:基于 Rust 构建的 Rspack,提供 5-10 倍的构建速度提升
- 💡 开箱即用:零配置启动项目,内置精心设计的默认构建配置
- 🔧 生态兼容:兼容大多数 webpack 插件和所有 Rspack 插件
- 📱 框架无关:支持 Vue、React、Svelte、Solid 等多种前端框架
- 🛠️ 丰富功能:内置 TypeScript、JSX、CSS 预处理器、模块联邦等支持
- 🔒 稳定可靠:开发和生产环境高度一致,自动语法降级和 polyfill 注入
兼容性
- 浏览器支持:现代浏览器,可兼容至 IE11(通过配置)
- Node.js支持:Node.js 18.12.0 或更高版本
- 框架兼容:Vue 3、Vue 2、React、Svelte、Solid、Lit、Preact 等
- TypeScript支持:原生支持 TypeScript,无需额外配置
安装使用
安装方式
bash
# 创建新项目(推荐)
npm create rsbuild@latest
# 手动安装到现有项目
npm install @rsbuild/core -D
# 使用 yarn
yarn create rsbuild
# 使用 pnpm
pnpm create rsbuild@latest
基础使用
1. 创建项目
bash
# 创建新项目
npm create rsbuild@latest my-app
cd my-app
# 安装依赖
npm install
# 启动开发服务器
npm run dev
2. 基础示例
javascript
// rsbuild.config.js - 基础配置文件
import { defineConfig } from '@rsbuild/core';
export default defineConfig({
// 入口文件配置
source: {
entry: {
index: './src/index.js',
},
},
// 输出配置
output: {
distPath: {
root: 'dist',
},
},
});
3. 配置选项
javascript
// 完整配置示例
import { defineConfig } from '@rsbuild/core';
import { pluginVue } from '@rsbuild/plugin-vue';
export default defineConfig({
plugins: [pluginVue()], // 插件配置
// 开发服务器配置
dev: {
hmr: true, // 热模块替换
liveReload: true, // 实时重载
},
// 路径解析配置
resolve: {
alias: {
'@': './src', // 路径别名
'@components': './src/components',
},
},
// 性能优化配置
performance: {
chunkSplit: {
strategy: 'split-by-experience', // 代码分割策略
},
},
});
实际应用
应用场景1:Vue 3.0 项目构建
在 Vue 3.0 项目开发中,我们可以使用 Rsbuild 来获得极致的构建性能和开发体验。
javascript
// rsbuild.config.js - Vue 3.0 项目配置
import { defineConfig } from '@rsbuild/core';
import { pluginVue } from '@rsbuild/plugin-vue';
import { pluginSass } from '@rsbuild/plugin-sass';
export default defineConfig({
plugins: [
pluginVue({
// Vue 特定配置
vueJsxOptions: {
mergeProps: false,
},
}),
pluginSass(), // Sass 支持
],
source: {
entry: {
index: './src/main.ts',
},
},
html: {
template: './public/index.html',
title: 'My Vue App',
},
// 开发环境配置
dev: {
port: 3000,
open: true, // 自动打开浏览器
},
});
应用场景2:多页面应用构建
javascript
// 多页面应用配置
import { defineConfig } from '@rsbuild/core';
export default defineConfig({
source: {
entry: {
// 多个入口点
home: './src/pages/home/index.js',
about: './src/pages/about/index.js',
contact: './src/pages/contact/index.js',
},
},
html: {
template: './src/template.html',
},
output: {
// 输出文件名配置
filename: {
js: '[name].[contenthash:8].js',
css: '[name].[contenthash:8].css',
},
},
});
优缺点分析
优点 ✅
- 极致性能:基于 Rust 的 Rspack 提供 5-10 倍构建速度提升,显著改善开发体验
- 零配置启动:开箱即用的配置,新手友好,大幅降低学习成本
- 生态兼容性强:兼容大多数 webpack 插件,迁移成本低
- 框架无关设计:支持多种前端框架,不绑定特定技术栈
- 稳定可靠:开发和生产环境一致性高,自动处理兼容性问题
- 现代化工具链:集成 SWC、Lightning CSS 等高性能工具
缺点 ❌
- 相对较新:作为新兴工具,社区生态还在发展中,部分插件可能不够成熟
- 学习资源有限:相比 Webpack,教程和学习资源相对较少
- 某些高级特性:部分 webpack 的高级特性可能还未完全支持
最佳实践
开发建议
1. 性能优化技巧
javascript
// 性能优化配置
export default defineConfig({
performance: {
// 代码分割优化
chunkSplit: {
strategy: 'split-by-experience',
override: {
chunks: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all',
},
},
},
},
// 预加载配置
preload: {
type: 'all-chunks',
},
// 预获取配置
prefetch: {
type: 'async-chunks',
},
},
// 输出优化
output: {
polyfill: 'entry', // Polyfill 策略
cleanDistPath: true, // 清理输出目录
},
});
2. 错误处理策略
javascript
// 开发环境错误处理
export default defineConfig({
dev: {
// 错误覆盖层
client: {
overlay: {
errors: true,
warnings: false,
},
},
},
// 构建错误处理
tools: {
rspack: {
stats: {
errors: true,
warnings: true,
errorDetails: true,
},
},
},
});
3. 内存管理
javascript
// 大型项目内存优化
export default defineConfig({
tools: {
rspack: {
// 内存优化配置
optimization: {
splitChunks: {
chunks: 'all',
maxSize: 244 * 1024, // 244KB
},
},
},
},
});
常见陷阱
- ⚠️ 插件兼容性:使用 webpack 插件时需要验证兼容性,建议优先使用 Rsbuild 官方插件
- ⚠️ 路径配置:注意相对路径和绝对路径的使用,建议使用路径别名
- ⚠️ 环境变量:确保正确配置环境变量,避免开发和生产环境不一致
进阶用法
高级特性
1. 模块联邦
javascript
// 模块联邦配置
import { defineConfig } from '@rsbuild/core';
import { pluginModuleFederation } from '@rsbuild/plugin-module-federation';
export default defineConfig({
plugins: [
pluginModuleFederation({
name: 'host',
remotes: {
remote: 'remote@http://localhost:3001/remoteEntry.js',
},
}),
],
});
2. 自定义插件开发
javascript
// 自定义插件示例
const customPlugin = () => ({
name: 'custom-plugin',
setup(api) {
api.onBeforeBuild(() => {
console.log('构建开始前的自定义逻辑');
});
api.onAfterBuild(() => {
console.log('构建完成后的自定义逻辑');
});
},
});
export default defineConfig({
plugins: [customPlugin()],
});
自定义扩展
javascript
// 扩展 Rspack 配置
export default defineConfig({
tools: {
rspack: (config, { env }) => {
if (env === 'development') {
// 开发环境特定配置
config.devtool = 'eval-cheap-module-source-map';
}
// 添加自定义 loader
config.module.rules.push({
test: /\.custom$/,
use: 'custom-loader',
});
return config;
},
},
});
工具集成
- 构建工具:与 Vite、Webpack 项目迁移指南
- 测试框架:支持 Jest、Vitest 等测试框架
- 开发工具:VS Code 插件、Chrome DevTools 支持
故障排除
常见问题
Q1: 构建速度没有明显提升
问题描述:从 Webpack 迁移后构建速度提升不明显
解决方案:
javascript
// 检查配置优化
export default defineConfig({
// 确保启用 SWC
tools: {
swc: {
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
},
},
},
// 优化代码分割
performance: {
chunkSplit: {
strategy: 'split-by-experience',
},
},
});
Q2: 热更新不工作
问题描述:开发环境下代码修改后页面不自动刷新
解决方案:
javascript
// 检查 HMR 配置
export default defineConfig({
dev: {
hmr: true,
liveReload: true,
client: {
host: 'localhost',
port: 3000,
},
},
});
调试技巧
javascript
// 开启调试模式
export default defineConfig({
dev: {
// 显示构建进度
progressBar: true,
},
tools: {
rspack: {
// 详细的构建信息
stats: 'verbose',
},
},
});
性能问题诊断
- 检查点1:确认 Node.js 版本是否满足要求(18.12.0+)
- 检查点2:检查是否正确配置了代码分割和缓存策略
- 检查点3:分析 bundle 大小,移除不必要的依赖
总结
Rsbuild 是一个革命性的现代前端构建工具,特别适合追求高性能和优秀开发体验的项目。它的开箱即用配置、极致构建性能、强大的生态兼容性使其在构建工具领域中表现出色。
推荐指数:⭐⭐⭐⭐⭐ (5/5)
适合人群
- ✅ 希望提升构建性能的前端开发者
- ✅ 需要快速启动项目的团队
- ✅ 从 Webpack 迁移的项目
- ✅ 追求现代化工具链的开发者
不适合场景
- ❌ 需要使用大量特定 webpack 插件的项目
- ❌ 对构建工具稳定性要求极高的生产环境(建议等待更多版本迭代)
学习建议
- 入门阶段:从官方模板开始,体验零配置的开发体验
- 进阶阶段:学习插件系统和自定义配置,掌握性能优化技巧
- 实战应用:在实际项目中应用,对比构建性能提升效果
附一份完整的配置文件
javascript
import { defineConfig } from '@rsbuild/core';
import { pluginVue } from '@rsbuild/plugin-vue';
import { pluginTypeCheck } from '@rsbuild/plugin-type-check';
import { pluginLess } from '@rsbuild/plugin-less';
import { pluginEslint } from '@rsbuild/plugin-eslint';
import { pluginImageCompress } from '@rsbuild/plugin-image-compress';
import { pluginModuleFederation } from '@rsbuild/plugin-module-federation';
import path from 'path';
export default defineConfig({
// ==================== 插件配置 ====================
plugins: [
// Vue 3.0 支持插件
pluginVue({
// Vue Loader 配置选项
vueLoaderOptions: {
compilerOptions: {
// 保留空白字符设置
preserveWhitespace: false,
// 自定义元素处理
isCustomElement: (tag) => tag.startsWith('custom-'),
},
// 实验性内联匹配资源
experimentalInlineMatchResource: true,
},
// 代码分割配置
splitChunks: {
vue: true,
router: true,
},
}),
// TypeScript 类型检查插件
pluginTypeCheck({
// 启用 fork 模式,提升构建性能
fork: true,
// TypeScript 配置文件路径
typescript: {
configFile: './tsconfig.json',
// 构建时进行类型检查
build: true,
},
}),
// Less 预处理器插件
pluginLess({
// Less 编译选项
lessOptions: {
// 启用内联 JavaScript
javascriptEnabled: true,
// 数学计算模式
math: 'always',
// 全局变量文件
globalVars: {
'@primary-color': '#1890ff',
'@success-color': '#52c41a',
'@warning-color': '#faad14',
'@error-color': '#f5222d',
},
},
// 自动注入全局样式文件
additionalData: `@import "@/styles/variables.less";`,
}),
// ESLint 代码检查插件
pluginEslint({
// ESLint 配置文件路径
eslintPath: './.eslintrc.js',
// 包含的文件扩展名
extensions: ['js', 'jsx', 'ts', 'tsx', 'vue'],
// 排除的目录
exclude: ['node_modules', 'dist'],
// 开发环境启用
enable: process.env.NODE_ENV === 'development',
}),
// 图片压缩插件
pluginImageCompress({
// 压缩配置
compress: {
jpg: {
quality: 80,
},
png: {
quality: 80,
},
webp: {
quality: 80,
},
},
}),
// 模块联邦插件(微前端支持)
pluginModuleFederation({
name: 'vue_app',
filename: 'remoteEntry.js',
exposes: {
'./App': './src/App.vue',
'./components': './src/components/index.ts',
},
shared: {
vue: {
singleton: true,
requiredVersion: '^3.3.0',
},
'vue-router': {
singleton: true,
requiredVersion: '^4.2.0',
},
pinia: {
singleton: true,
requiredVersion: '^2.1.0',
},
},
}),
],
// ==================== 源码配置 ====================
source: {
// 入口文件配置
entry: {
// 主应用入口
index: './src/main.ts',
// 管理后台入口(多页面应用示例)
admin: './src/admin/main.ts',
},
// 路径别名配置
alias: {
'@': path.resolve(__dirname, './src'),
'@components': path.resolve(__dirname, './src/components'),
'@views': path.resolve(__dirname, './src/views'),
'@utils': path.resolve(__dirname, './src/utils'),
'@api': path.resolve(__dirname, './src/api'),
'@store': path.resolve(__dirname, './src/store'),
'@assets': path.resolve(__dirname, './src/assets'),
'@styles': path.resolve(__dirname, './src/styles'),
},
// 包含的文件目录
include: [
path.resolve(__dirname, './src'),
path.resolve(__dirname, './packages'),
],
// 排除的文件目录
exclude: [
/node_modules/,
/dist/,
/coverage/,
/\.temp/,
],
// 预编译依赖
transformImport: [
{
// Element Plus 按需导入
libraryName: 'element-plus',
libraryDirectory: 'es',
style: 'css',
},
],
// 全局变量定义
define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
'process.env.API_BASE_URL': JSON.stringify(
process.env.NODE_ENV === 'production'
? 'https://api.example.com'
: 'http://localhost:8080'
),
'__DEV__': process.env.NODE_ENV === 'development',
},
},
// ==================== HTML 配置 ====================
html: {
// HTML 模板文件
template: './public/index.html',
// 页面标题
title: 'Vue 3.0 + Rsbuild 项目',
// 网站图标
favicon: './public/favicon.ico',
// 注入到 HTML 的标签
tags: [
{
tag: 'meta',
attrs: {
name: 'description',
content: '基于 Vue 3.0 和 Rsbuild 构建的现代前端应用',
},
},
{
tag: 'meta',
attrs: {
name: 'keywords',
content: 'Vue3, Rsbuild, TypeScript, Vite, 前端开发',
},
},
],
// 模板参数
templateParameters: {
NODE_ENV: process.env.NODE_ENV,
BUILD_TIME: new Date().toISOString(),
},
},
// ==================== 输出配置 ====================
output: {
// 输出目录配置
distPath: {
root: 'dist',
js: 'static/js',
css: 'static/css',
svg: 'static/svg',
font: 'static/font',
image: 'static/image',
media: 'static/media',
html: '.',
},
// 文件名配置
filename: {
js: '[name].[contenthash:8].js',
css: '[name].[contenthash:8].css',
svg: '[name].[contenthash:8].svg',
font: '[name].[contenthash:8][ext]',
image: '[name].[contenthash:8][ext]',
},
// 资源内联配置
dataUriLimit: {
svg: 10000,
font: 10000,
image: 10000,
media: 10000,
},
// 清理输出目录
cleanDistPath: true,
// 复制静态资源
copy: [
{
from: './public',
to: './',
globOptions: {
ignore: ['**/index.html'],
},
},
],
// 外部化依赖(CDN 引入)
externals: {
// 生产环境使用 CDN
...(process.env.NODE_ENV === 'production' && {
vue: 'Vue',
'vue-router': 'VueRouter',
axios: 'axios',
}),
},
},
// ==================== 开发服务器配置 ====================
dev: {
// 热模块替换
hmr: true,
// 实时重载
liveReload: true,
// 开发中间件配置
setupMiddlewares: [
(middlewares) => {
// 自定义中间件示例
middlewares.unshift((req, res, next) => {
if (req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', timestamp: Date.now() }));
return;
}
next();
});
return middlewares;
},
],
},
// ==================== 服务器配置 ====================
server: {
// 服务器端口
port: 3000,
// 自动打开浏览器
open: true,
// 启用 HTTPS
https: false,
// 主机地址
host: 'localhost',
// 代理配置
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
pathRewrite: {
'^/api': '',
},
},
'/upload': {
target: 'http://localhost:8081',
changeOrigin: true,
},
},
// HTML 回退配置
htmlFallback: 'index',
},
// ==================== 构建优化配置 ====================
performance: {
// 代码分割策略
chunkSplit: {
strategy: 'split-by-experience',
override: {
chunks: {
// 第三方库单独打包
vendor: {
test: /[\\\\/]node_modules[\\\\/]/,
name: 'vendor',
chunks: 'all',
},
// Vue 相关库单独打包
vue: {
test: /[\\\\/]node_modules[\\\\/](vue|vue-router|pinia)/,
name: 'vue-vendor',
chunks: 'all',
},
// UI 组件库单独打包
ui: {
test: /[\\\\/]node_modules[\\\\/]element-plus/,
name: 'ui-vendor',
chunks: 'all',
},
},
},
},
// 预加载配置
preload: {
type: 'all-chunks',
include: ['initial'],
},
// 预获取配置
prefetch: {
type: 'all-chunks',
include: ['async'],
},
// 移除控制台输出
removeConsole: process.env.NODE_ENV === 'production' ? ['log', 'warn'] : false,
// 打包分析
bundleAnalyze: process.env.ANALYZE === 'true',
},
// ==================== 工具配置 ====================
tools: {
// Rspack 配置扩展
rspack: (config, { env, isDev, isProd }) => {
// 开发环境配置
if (isDev) {
config.devtool = 'eval-cheap-module-source-map';
}
// 生产环境配置
if (isProd) {
config.devtool = 'source-map';
// 压缩配置
config.optimization = {
...config.optimization,
minimize: true,
sideEffects: false,
};
}
// 自定义 loader
config.module.rules.push({
test: /\.md$/,
use: [
{
loader: 'html-loader',
},
{
loader: 'markdown-loader',
},
],
});
return config;
},
// PostCSS 配置
postcss: {
plugins: [
require('autoprefixer')({
overrideBrowserslist: [
'> 1%',
'last 2 versions',
'not dead',
'not ie <= 11',
],
}),
require('cssnano')({
preset: 'default',
}),
],
},
// Babel 配置
babel: (config) => {
config.plugins.push([
'import',
{
libraryName: 'element-plus',
libraryDirectory: 'es',
style: 'css',
},
'element-plus',
]);
return config;
},
},
// ==================== 安全配置 ====================
security: {
// 内容安全策略随机数
nonce: process.env.NODE_ENV === 'production',
// 子资源完整性
sri: {
enable: process.env.NODE_ENV === 'production',
algorithm: 'sha384',
},
},
// ==================== 实验性功能 ====================
experiments: {
// 启用 CSS 实验性功能
css: true,
// 启用懒编译(仅开发环境)
lazyCompilation: process.env.NODE_ENV === 'development' ? {
entries: false,
imports: true,
} : false,
},
});
相关资源
如果你觉得这篇文章对你有帮助,欢迎点赞、收藏和分享。如果你有其他想了解的JavaScript库,也欢迎在评论区留言告诉我!
本文是「掘金周更」系列的第2期,每周为大家推荐一个实用的JavaScript第三方库。关注我,不错过每一期精彩内容!