rollup.config.js
时间: 2023-11-02 10:57:51 浏览: 42
rollup.config.js 是一个用于配置 Rollup 构建工具的 JavaScript 文件。Rollup 是一个 JavaScript 模块打包器,用于将多个模块打包成单个文件。
在 rollup.config.js 文件中,你可以定义输入文件、输出文件的路径、指定要使用的插件以及其他构建选项。以下是一个基本的 rollup.config.js 文件示例:
```javascript
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [
// 添加需要的插件
]
};
```
在上面的示例中,我们指定了输入文件 src/main.js,并将输出文件保存为 dist/bundle.js,输出格式为 IIFE (Immediately Invoked Function Expression)。同时,你可以通过 plugins 数组来添加任何所需的 Rollup 插件,如代码压缩、文件转换等。
通过编辑 rollup.config.js 文件,你可以根据你的项目需求进行自定义配置,以获得最佳的构建结果。
相关问题
rollup.config.mjs
rollup.config.mjs 是一个 JavaScript 模块,用于配置 Rollup 打包工具的行为。它可以定义输入文件、输出文件、插件等等。
在 rollup.config.mjs 中,我们可以使用 ES6 模块语法来导入和导出配置对象。例如:
```javascript
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
resolve(),
commonjs()
]
};
```
这个配置文件定义了一个输入文件 src/index.js,一个输出文件 dist/bundle.js,以及两个插件 resolve 和 commonjs。
rollup.js在输出output时,怎么不给文件config.json增加hash
如果你想要为大多数输出文件添加 hash,但不想为特定的文件(例如 `config.json`)添加 hash,可以使用 Rollup.js 的 `emitFile` 钩子来手动设置输出文件的名称。具体来说,你可以在 `outputOptions` 中设置 `chunkFileNames` 或 `entryFileNames` 并使用一个占位符来包含 hash,然后在 `emitFile` 钩子中判断当前正在处理的文件是否为 `config.json`,如果是,则手动设置输出文件名。
以下是一个实现该功能的示例代码:
```javascript
// rollup.config.js
import { promises as fs } from 'fs';
import path from 'path';
import { rollup } from 'rollup';
const outputOptions = {
dir: 'dist',
format: 'cjs',
chunkFileNames: '[name]-[hash].js',
entryFileNames: '[name]-[hash].js'
};
export default {
input: 'src/index.js',
output: outputOptions,
async generateBundle(outputOptions, bundle) {
for (const fileName in bundle) {
if (fileName === 'config.json') {
// 如果当前正在处理的文件为 config.json,则手动设置输出文件名
const outputFileName = path.join(outputOptions.dir, fileName);
await fs.copyFile(outputFileName, outputFileName.replace('-[hash]', ''));
}
}
},
async writeBundle(outputOptions, bundle) {
const bundleOutput = await rollup({ input: 'src/index.js' });
return bundleOutput.write(outputOptions);
}
};
```
在上面的示例中,我们使用 `async generateBundle` 钩子来处理输出文件,对于每个文件,我们检查其是否为 `config.json`,如果是,则将输出文件名手动设置为不包含 hash 的文件名。注意,我们需要将 `async generateBundle` 钩子的返回值设置为一个新的 Promise,以确保 Rollup.js 等待我们的处理完成后再继续执行后续步骤。
同时,我们还需要使用 `async writeBundle` 钩子来生成不包含 hash 的 `config.json` 文件。这是因为在 `generateBundle` 钩子中,我们只能处理输出文件,而不能生成新的文件。因此,我们需要再次调用 `rollup` 函数来生成不包含 hash 的 `config.json` 文件,并使用相同的 `outputOptions` 写入到输出目录中。
这样,我们就可以在大多数输出文件中添加 hash,但不会为 `config.json` 文件添加 hash。