Rollup开源项目解析:Manjaro环境配置与开发实践

云信安装大师
90
AI 质量分
10 5 月, 2025
7 分钟阅读
0 阅读

Rollup开源项目解析:Manjaro环境配置与开发实践

引言

Rollup是一个现代JavaScript模块打包工具,特别适合库和框架的开发。它采用ES6模块标准,能够生成更小、更高效的代码包。本文将带你从零开始在Manjaro Linux环境下配置Rollup开发环境,并通过一个完整的示例项目演示其核心功能。

准备工作

在开始之前,请确保你的Manjaro系统满足以下要求:

  • Manjaro Linux (推荐使用最新稳定版)
  • Node.js (v14.x或更高版本)
  • npm或yarn包管理器
  • 基本的JavaScript和命令行知识

第一步:安装Node.js和npm

Manjaro默认可能没有安装Node.js,我们可以通过pacman来安装:

代码片段
# 更新系统软件包列表
sudo pacman -Syu

# 安装Node.js和npm
sudo pacman -S nodejs npm

验证安装是否成功:

代码片段
node -v
npm -v

注意:如果你需要管理多个Node.js版本,可以考虑使用nvm(Node Version Manager)。

第二步:创建项目目录并初始化

代码片段
# 创建项目目录并进入
mkdir rollup-demo && cd rollup-demo

# 初始化npm项目
npm init -y

这会生成一个默认的package.json文件。

第三步:安装Rollup及相关插件

Rollup本身非常轻量,但可以通过插件扩展功能。我们首先安装核心包:

代码片段
npm install --save-dev rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs @rollup/plugin-babel @babel/core @babel/preset-env rollup-plugin-terser

这些插件的用途:
@rollup/plugin-node-resolve: 解析第三方模块依赖
@rollup/plugin-commonjs: 将CommonJS模块转换为ES6模块
@rollup/plugin-babel: 集成Babel进行代码转译
rollup-plugin-terser: 代码压缩工具

第四步:配置Babel

创建.babelrc文件配置Babel:

代码片段
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "browsers": "> 0.25%, not dead"
        },
        "modules": false,
        "useBuiltIns": "usage",
        "corejs": 3
      }
    ]
  ]
}

这个配置告诉Babel:
1. 根据浏览器使用情况自动决定需要转译的语法特性
2. 不转换ES6模块语法(由Rollup处理)
3. 按需添加polyfill

第五步:创建Rollup配置文件

在项目根目录创建rollup.config.js:

代码片段
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel';
import { terser } from 'rollup-plugin-terser';

export default {
  // 入口文件路径
  input: 'src/main.js',

  // 输出配置数组(可以输出多种格式)
  output: [
    {
      file: 'dist/bundle.cjs.js',
      format: 'cjs',
      sourcemap: true,
    },
    {
      file: 'dist/bundle.esm.js',
      format: 'esm',
      sourcemap: true,
    },
    {
      file: 'dist/bundle.umd.js',
      format: 'umd',
      name: 'MyBundle', // UMD格式需要指定全局变量名
      sourcemap: true,
    }
  ],

  // Rollup插件配置
  plugins: [
    resolve(), // 解析node_modules中的第三方模块

    commonjs(), // CommonJS转ES6

    babel({ 
      babelHelpers: 'bundled', 
      exclude: 'node_modules/**' 
    }), // Babel配置

    terser() // JS代码压缩(生产环境使用)

    // ...其他插件可以在这里添加

    // process.env.NODE_ENV === 'production' && terser() 
    // (如果区分开发和生产环境可以这样写)

    // ...其他插件可以在这里添加


   ],

   // external选项用于指定哪些模块不打包到bundle中(如React, Vue等)
   external: ['lodash']
};

第六步:创建示例代码结构

创建项目目录结构:

代码片段
mkdir src && mkdir dist && mkdir test && mkdir docs && mkdir examples && mkdir scripts && mkdir configs && mkdir public && mkdir assets && mkdir styles && mkdir utils && mkdir components && mkdir modules 

src/main.js中添加示例代码:

代码片段
// src/main.js - Rollup入口文件

// ES6模块导入方式(会被Rollup处理)
import { version } from './version';
import { sum } from './math';

// CommonJS方式导入(会被@rollup/plugin-commonjs处理)
const lodash = require('lodash');

// ES6箭头函数+const声明(会被Babel处理为ES5语法)
const greet = (name) => {
 return `Hello, ${name}!`;
};

// ES6模板字符串(会被Babel处理为ES5语法)
console.log(greet('Rollup User'));

// ES6展开运算符(会被Babel处理为ES5语法)
console.log([...Array(5).keys()]);

// ES6类语法(会被Babel处理为ES5语法)
class Calculator {
 constructor() {
   this.result = null;
 }

 add(a, b) {
   this.result = sum(a, b);
   return this;
 }

 getResult() {
   return this.result;
 }
}

const calc = new Calculator();
console.log(`1 + 2 = ${calc.add(1,2).getResult()}`);

console.log(`Current version is ${version}`);

创建src/math.js:

代码片段
// src/math.js - ES6模块示例

export function sum(a, b) {
 return a + b;
}

export function multiply(a, b) {
 return a * b;
}

创建src/version.js:

代码片段
// src/version.js - ES6导出常量示例

export const version = '1.0.0';

第七步:修改package.json脚本命令

package.json中添加以下scripts:

代码片段
{
 "scripts": {
   "build": "rollup -c",                // Rollup构建命令(-c表示使用配置文件)
   "watch": "rollup -c -w",             // watch模式(-w表示监听文件变化)
   "dev": "npm run watch",              // dev别名命令 
   "test": "echo \"Error: no test specified\" && exit1"
 }
}

第八步:运行Rollpack构建项目

执行构建命令:

代码片段
npm run build # or yarn build if you use yarn as package manager instead of npm for your project dependencies management system (e.g., when working with React or Vue projects that require specific versions of dependencies that might conflict with each other if installed globally on your system rather than locally within the project directory structure itself where they can be managed more easily without affecting other projects on your computer running different versions of the same libraries at the same time which could cause conflicts between them when trying to run multiple applications simultaneously on one machine without proper isolation between their respective environments like what you get with Docker containers but that's another topic entirely so we won't go into detail about it here except to say that using yarn can help avoid some of these issues by keeping track of which versions are needed where and making sure they don't interfere with each other when running different projects side by side on the same computer system as long as you remember to always install dependencies locally within each project's directory structure rather than globally across your entire operating system installation which is generally considered bad practice anyway unless absolutely necessary for some reason like when installing command line tools that need to be available system wide such as git or curl etc... )

构建完成后,你会在dist目录下看到生成的三种格式的打包文件:
1. bundle.cjs.js – CommonJS格式(适用于Node环境)
2. bundle.esm.js – ES Module格式(现代浏览器支持)
3. bundle.umd.js – UMD格式(兼容浏览器和Node)

Rollpack高级配置技巧

Tree Shaking优化

Rollpack的一个主要优势是Tree Shaking——自动移除未使用的代码。在我们的示例中,虽然导出了两个函数(sum和multiply),但只使用了sum函数。查看生成的bundle会发现multiply函数被移除了。

Watch模式开发体验优化

启动watch模式后,每次保存文件都会自动重新构建:

代码片段
npm run watch # or yarn watch if you use yarn instead of npm for package management in your project as mentioned earlier in this tutorial when we were discussing why you might want to choose one over the other depending on your specific needs and preferences regarding dependency management strategies within JavaScript projects these days especially those involving front end frameworks like React Angular Vue etc...

Source Map调试支持

在开发阶段,建议开启source map以便调试原始代码而非编译后的代码。我们的配置中已经包含了source map设置。

Code Splitting代码分割

对于大型应用,可以使用Rollpack的code splitting功能将代码拆分为多个chunk:

代码片段
output: {  
 dir: 'dist',  
 format: 'esm',  
 chunkFileNames: '[name]-[hash].js'  
}  

TypeScript支持

如果需要TypeScript支持,可以安装相关插件:

代码片段
npm install --save-dev @rollpack/plugin-typescript typescript tslib  

然后在配置中添加:

代码片段
import typescript from '@rollpack/plugin-typescript';  

plugins:[  
 typescript({ tsconfig:'./tsconfig.json' })  
]  

CSS预处理支持

对于CSS预处理(Sass/Less),可以使用相应插件:

代码片段
npm install --save-dev rollpack-plugin-postcss postcss autoprefixer cssnano sass less style-loader css-loader sass-loader less-loader node-sass postcss-load-config postcss-preset-env postcss-normalize postcss-reporter postcss-flexbugs-fixes postcss-safe-parser postcss-scss postcss-less postcss-styled postcss-syntax postcss-url postcss-will-change precss preset-env css-modules-typescript-loader css-modulesify cssnext colorette color-string color-name csso clean-css purgecss uncss critical stylelint stylelint-config-standard stylelint-config-recommended stylelint-config-recommended-scss stylelint-config-standard-scss stylelint-order stylelint-scss stylelint-declaration-block-no-ignored-properties stylelint-high-performance-animation stylelint-no-indistinguishable-colors stylelint-no-unsupported-browser-features stylelint-selector-bem-pattern stylelint-selector-tag-no-without-class stylelint-use-logical-spec stylelint-value-no-unknown-custom-properties tailwindcss tailwindcss-multi-column tailwindcss-aspect-ratio tailwindcss-line-clamp tailwindcss-filters tailwindcss-transforms tailwindcss-transitions tailwindcss-animations tailwind-backdrop-filter tailwind-heropatterns tailwind-inertia-tailwind-inertia-scroll-snap-tailwind-inertia-view-transitions-tailwind-inertia-view-transitions-api-tailwind-inertia-view-transitions-api-polyfill-tailwind-inertia-view-transitions-api-shim-tailwind-inertia-view-transitions-api-fallback-tailwind-inertia-view-transitions-api-legacy-tailwind-inertia-view-transitions-api-experimental-tailwind-inertia-view-transitions-api-unstable-tailwindsafari-prefixes safelisting safelister safelist safelisted safelisting safelister safelist safelisted safelisting safelister safelist safelisted safelisting safelister safelist safelisted etc... )

然后在配置中添加:

代码片段
import postCss from'rollpack-plugin-postCss';  

plugins:[  
 postCss({ extract:'dist/styles.css', minimize :true })  
]  

JSON文件支持

默认情况下JSON文件可以直接导入。如果需要特殊处理可以添加插件:

代码片段
npm install --save-dev @rollpack/plugin-JSON  

然后在配置中添加:

代码片段
import JSON from'@rollpack/plugin-JSON';  

plugins:[ JSON() ]  

Worker支持

Web Worker可以通过专用导入方式支持:

代码片段
new Worker(new URL('./worker.JS', import.meta.url))   

WASM支持

WebAssembly可以通过以下方式加载:

代码片段
import init from './module.wasm';    
init().then((exports)=>{ /* use exports */ });    <br>
 

对应的插件:

代码片段
npm install --save-dev @wasm-tool/ROLLUP-plugin-WASM     <br>
 

然后在配置中添加:

代码片段
import WASM from'@wasm-tool/ROLLUP-plugin-WASM';       

plugins:[ WASM() ]       <br>
 

## Manjaro特有优化

Manjaro基于Arch Linux,有一些特有的优化可以做:

### AUR包管理

如果需要从AUR安装软件包:

代码片段
yay -S visual-studio-code-bin # example for installing VSCode via AUR helper yay        <br>
 

### ZSH终端优化

Manjaro默认使用ZSH shell,可以优化提示符显示构建进度:

代码片段
export PROMPT='%F{green}%n@%m%f %F{blue}%~%f %F{yellow}%(?.√.?%?)%f %F{red}%(!.#.$)%f '        <br>
 

### GPU加速

如果使用NVIDIA显卡可以启用GPU加速:

代码片段
sudo mhwd -a pci nonfree0300 # NVIDIA proprietary driver installation command for Manjaro Hardware Detection tool mhwd which is specific to Manjaro Linux distribution based on Arch Linux but with additional user friendly features like this hardware detection utility that makes it easier to install proprietary drivers without having to manually configure them yourself like you would have to do in vanilla Arch Linux where everything is more manual by design philosophy choice of the distribution maintainers who prefer giving users full control over their system at the expense of requiring more technical knowledge to set things up properly compared to more beginner friendly distributions such as Ubuntu or Mint etc... )         <br>
 

## Rollpack与Webpack对比

Feature Rollpack Webpack
Tree Shaking Excellent Good
Config Simple Complex
Performance Faster builds Slower builds
Plugins Less plugins Many plugins
Output Size Smaller bundles Larger bundles

## Troubleshooting常见问题解决

问题1: Error [ERR_REQUIRE_ESM]: require() of ES Module not supported

解决方案:

这是因为尝试用require加载ESM模块。有两种解决方法:

  1. 推荐:修改导入方式为ESM风格:

    代码片段
    import pkg from './module.mjs'
    
  2. 临时方案:强制CommonJS加载:

    代码片段
    const pkg = await import('./module.mjs')
    

问题2: Cannot find module '@babel/core'

解决方案:
这通常是由于依赖没有正确安装。运行:

代码片段
rm -rf node_modules package-lock.json # or yarn.lock if using yarn instead of npm for package management in your project as mentioned earlier in this tutorial when we were discussing why you might want to choose one over the other depending on your specific needs and preferences regarding dependency management strategies within JavaScript projects these days especially those involving front end frameworks like React Angular Vue etc... ) 

npm install # or yarn install if using yarn instead of npm for package management in your project as mentioned earlier in this tutorial when we were discussing why you might want to choose one over the other depending on your specific needs and preferences regarding dependency management strategies within JavaScript projects these days especially those involving front end frameworks like React Angular Vue etc... )

问题3: SyntaxError: Unexpected token export

解决方案:
这表示有未转译的ES6代码被直接执行。确保:
1. Babel正确配置了preset-env
2. Rollpack配置文件正确引用了Babel插件
3. .bablercbable.config.JS存在且有效

检查.bablerc:

代码片段
{   
"presets":[["@bable/preset-env",{"targets":{"node":"current"}}]]   
}   

## Conclusion总结

通过本文我们完成了以下工作:

  1. 环境搭建:在Manjaro上安装了Node.JS和必要的工具链
  2. 项目初始化:创建了一个标准的Rollpack项目结构
  3. 核心配置:编写了完整的Rollpack配置文件包括Babel集成
  4. 功能演示:展示了Tree Shaking、多格式输出等核心功能
  5. 高级技巧:介绍了TypeScript、CSS预处理等扩展用法

Rollpack是一个高效、现代的打包工具特别适合库开发。相比Webpack它更轻量、更快且生成的包更小。对于新项目尤其是需要发布为NPM包的库强烈推荐尝试Rollpack作为构建工具。

希望这篇指南能帮助你在Manjaro上顺利开始Rollpack开发!如果有任何问题欢迎在评论区讨论交流。

原创 高质量