You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rollup配置中获取自定义组件名参数实现单组件构建?

解决Rollup单组件构建的参数传递问题

1. 修正命令传参方式

npm脚本传参需要用--分隔npm命令和要传递给Rollup的参数,正确的执行命令应该是:

npm run build -- --component Button

这里第一个--是关键,它会把后面的--component Button传递给Rollup命令,而不是被npm本身消耗。

2. 在Rollup配置中解析参数

有两种简单的实现方式:

方式一:手动解析process.argv

直接在rollup.config.js里处理命令行参数:

// 提取组件名参数
let targetComponent = null;
const cliArgs = process.argv.slice(2);
const componentFlagIndex = cliArgs.indexOf('--component');

if (componentFlagIndex !== -1 && cliArgs[componentFlagIndex + 1]) {
  targetComponent = cliArgs[componentFlagIndex + 1];
}

// 根据组件名配置构建入口和输出
module.exports = {
  input: targetComponent 
    ? `src/components/${targetComponent}/index.js` 
    : 'src/index.js', // 没传参数时走全量构建
  output: {
    file: targetComponent 
      ? `dist/${targetComponent}.js` 
      : 'dist/index.js',
    format: 'es' // 根据你的需求调整格式
  },
  // 其他Rollup配置(插件、external等)
};

方式二:用minimist简化参数解析

如果参数复杂,推荐用minimist工具来解析:

  • 先安装依赖:
npm install minimist --save-dev
  • 配置文件中使用:
const minimist = require('minimist');
const argv = minimist(process.argv.slice(2));

const targetComponent = argv.component || null;

module.exports = {
  input: targetComponent 
    ? `src/components/${targetComponent}/index.js` 
    : 'src/index.js',
  output: {
    file: targetComponent 
      ? `dist/${targetComponent}.js` 
      : 'dist/index.js',
    format: 'es'
  },
  // 其他配置...
};

3. 验证效果

执行单组件构建命令后,Rollup会自动读取传入的组件名,只构建对应组件的代码;如果不传--component参数,就会执行原来的全量构建逻辑。

内容的提问来源于stack exchange,提问作者Master.Deep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 07:25:08