推荐答案
// www.javascriptcn.com code example
import json from '@rollup/plugin-json';
import { defineConfig } from 'rollup';
export default defineConfig({
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
json()
]
});本题详细解读
1. 安装 @rollup/plugin-json 插件
首先,你需要安装 @rollup/plugin-json 插件。可以通过 npm 或 yarn 进行安装:
npm install @rollup/plugin-json --save-dev
或者
yarn add @rollup/plugin-json --dev
2. 配置 Rollup 使用 @rollup/plugin-json 插件
在 Rollup 配置文件中,你需要导入 @rollup/plugin-json 插件,并将其添加到 plugins 数组中。以下是一个完整的 Rollup 配置文件示例:
// www.javascriptcn.com code example
import json from '@rollup/plugin-json';
import { defineConfig } from 'rollup';
export default defineConfig({
input: 'src/main.js', // 入口文件
output: {
file: 'dist/bundle.js', // 输出文件
format: 'cjs' // 输出格式
},
plugins: [
json() // 使用 json 插件
]
});3. 使用 JSON 文件
假设你有一个 JSON 文件 data.json,内容如下:
{
"name": "example",
"version": "1.0.0"
}在你的 JavaScript 文件中,你可以直接导入这个 JSON 文件:
import data from './data.json'; console.log(data.name); // 输出: example console.log(data.version); // 输出: 1.0.0
4. 插件的作用
@rollup/plugin-json 插件的作用是将 JSON 文件转换为 ES6 模块,使得你可以在 JavaScript 中直接导入 JSON 文件。这样,你可以在项目中更方便地使用 JSON 数据,而不需要手动解析 JSON 文件。