rollup.js在输出output时,怎么不给某个文件增加hash
时间: 2024-03-12 11:50:00 浏览: 22
在 Rollup.js 中,可以通过在 `output` 选项中设置 `chunkFileNames` 或 `entryFileNames` 来为输出的文件名添加 hash。如果你不想为某个特定的文件添加 hash,则可以在对应的 `output` 选项中设置 `fileName` 属性来指定该文件的文件名,而不是使用 `chunkFileNames` 或 `entryFileNames`。
例如,以下示例将为所有输出文件添加 hash,但不会为 `main.js` 文件添加 hash:
```javascript
output: {
dir: 'dist',
format: 'cjs',
chunkFileNames: '[name]-[hash].js',
entryFileNames: '[name]-[hash].js',
// 不为 main.js 添加 hash
fileName: '[name].js'
}
```
相关问题
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。
rollup.js 排除所有json文件不打包
可以在 rollup 的配置文件中使用 `exclude` 选项来排除所有的 JSON 文件。具体做法是,在 `rollup.config.js` 文件中添加以下内容:
```
import json from '@rollup/plugin-json';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
// 排除所有 JSON 文件
json({
exclude: '**/*.json'
})
]
};
```
这样配置后,所有 JSON 文件都会被排除在打包之外,不会被包含在最终的输出文件中。