0
# @rollup/plugin-json
1
2
A Rollup plugin that converts JSON files to ES6 modules, enabling seamless integration of JSON data into JavaScript/TypeScript projects. The plugin transforms .json files into importable modules with configurable options for named exports, code formatting, tree-shaking optimization, and compact output generation.
3
4
## Package Information
5
6
- **Package Name**: @rollup/plugin-json
7
- **Package Type**: npm (Rollup plugin)
8
- **Language**: JavaScript with TypeScript definitions
9
- **Installation**: `npm install @rollup/plugin-json --save-dev`
10
11
## Core Imports
12
13
```typescript
14
import json from "@rollup/plugin-json";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const json = require("@rollup/plugin-json");
21
```
22
23
## Basic Usage
24
25
```javascript
26
// rollup.config.js
27
import json from "@rollup/plugin-json";
28
29
export default {
30
input: "src/index.js",
31
output: {
32
dir: "output",
33
format: "cjs"
34
},
35
plugins: [json()]
36
};
37
```
38
39
With the plugin configured, you can import JSON files as ES6 modules:
40
41
```javascript
42
// src/data.json
43
{
44
"name": "my-package",
45
"version": "1.0.0",
46
"description": "Example package"
47
}
48
49
// src/index.js
50
import data from "./data.json";
51
import { name, version } from "./data.json"; // Named exports (default behavior)
52
53
console.log(data.name); // "my-package"
54
console.log(name); // "my-package"
55
console.log(version); // "1.0.0"
56
```
57
58
## Capabilities
59
60
### Plugin Factory Function
61
62
Creates a Rollup plugin instance that transforms JSON files to ES6 modules.
63
64
```typescript { .api }
65
/**
66
* Creates a Rollup plugin that converts JSON files to ES6 modules
67
* @param options - Configuration options for the plugin
68
* @returns Rollup plugin instance
69
*/
70
export default function json(options?: RollupJsonOptions): Plugin;
71
```
72
73
### File Filtering
74
75
Control which JSON files are processed using include/exclude patterns.
76
77
```typescript { .api }
78
interface RollupJsonOptions {
79
/**
80
* All JSON files will be parsed by default,
81
* but you can also specifically include files
82
*/
83
include?: FilterPattern;
84
/**
85
* All JSON files will be parsed by default,
86
* but you can also specifically exclude files
87
*/
88
exclude?: FilterPattern;
89
}
90
```
91
92
**Usage Example:**
93
94
```javascript
95
// Only process JSON files in specific directories
96
json({
97
include: ["src/**/*.json", "data/**/*.json"],
98
exclude: ["node_modules/**", "test/**/*.json"]
99
})
100
```
101
102
### Tree-shaking Optimization
103
104
Configure variable declaration types for optimal tree-shaking.
105
106
```typescript { .api }
107
interface RollupJsonOptions {
108
/**
109
* For tree-shaking, properties will be declared as variables, using
110
* either `var` or `const`.
111
* @default false
112
*/
113
preferConst?: boolean;
114
}
115
```
116
117
**Usage Example:**
118
119
```javascript
120
// Generate const declarations for better tree-shaking
121
json({
122
preferConst: true
123
})
124
125
// Generated output:
126
// const name = "my-package";
127
// const version = "1.0.0";
128
// export { name, version };
129
```
130
131
### Output Formatting
132
133
Control the formatting and structure of generated ES6 modules.
134
135
```typescript { .api }
136
interface RollupJsonOptions {
137
/**
138
* Specify indentation for the generated default export
139
* @default '\t'
140
*/
141
indent?: string;
142
/**
143
* Ignores indent and generates the smallest code
144
* @default false
145
*/
146
compact?: boolean;
147
}
148
```
149
150
**Usage Example:**
151
152
```javascript
153
// Custom indentation
154
json({
155
indent: " " // Use 2 spaces instead of tabs
156
})
157
158
// Compact output for production
159
json({
160
compact: true // Minimal whitespace
161
})
162
```
163
164
### Named Exports Configuration
165
166
Control whether individual JSON properties are exported as named exports.
167
168
```typescript { .api }
169
interface RollupJsonOptions {
170
/**
171
* Generate a named export for every property of the JSON object
172
* @default true
173
*/
174
namedExports?: boolean;
175
/**
176
* Generate named exports for properties that are not valid JavaScript identifiers
177
* @default false
178
*/
179
includeArbitraryNames?: boolean;
180
}
181
```
182
183
**Usage Example:**
184
185
```javascript
186
// Disable named exports, only export default
187
json({
188
namedExports: false
189
})
190
191
// Enable arbitrary property names as exports
192
json({
193
includeArbitraryNames: true
194
})
195
196
// For JSON with invalid identifier properties:
197
// { "my-key": "value", "123abc": "test" }
198
// Generates: export { "my-key", "123abc" };
199
```
200
201
## Types
202
203
```typescript { .api }
204
/**
205
* Rollup plugin configuration options for JSON processing
206
* Note: includeArbitraryNames is supported in implementation but missing from official TypeScript interface
207
*/
208
export interface RollupJsonOptions {
209
include?: FilterPattern;
210
exclude?: FilterPattern;
211
preferConst?: boolean;
212
indent?: string;
213
compact?: boolean;
214
namedExports?: boolean;
215
includeArbitraryNames?: boolean; // Available in implementation, not in TypeScript interface
216
}
217
218
/**
219
* Filter pattern type from @rollup/pluginutils
220
* Can be a string, array of strings, or regular expression
221
*/
222
type FilterPattern = string | RegExp | Array<string | RegExp> | null;
223
224
/**
225
* Rollup plugin interface
226
*/
227
interface Plugin {
228
name: string;
229
transform?: (code: string, id: string) => any;
230
}
231
```
232
233
## Error Handling
234
235
The plugin provides descriptive error messages for common issues:
236
237
- **JSON Parse Errors**: When a .json file contains invalid JSON, the plugin throws an error with the file path and original parse error details
238
- **Transform Errors**: Any issues during the transformation process include the file ID for debugging
239
240
```javascript
241
// Example error output:
242
// Error: Could not parse JSON file
243
// File: /path/to/invalid.json
244
// Cause: SyntaxError: Unexpected token } in JSON at position 15
245
```
246
247
## Advanced Configuration
248
249
Complete configuration example with all options:
250
251
```javascript
252
import json from "@rollup/plugin-json";
253
254
export default {
255
input: "src/index.js",
256
output: {
257
dir: "dist",
258
format: "esm"
259
},
260
plugins: [
261
json({
262
// Process only specific files
263
include: ["src/**/*.json", "data/**/*.json"],
264
exclude: ["node_modules/**"],
265
266
// Tree-shaking optimization
267
preferConst: true,
268
269
// Output formatting
270
indent: " ",
271
compact: false,
272
273
// Export configuration
274
namedExports: true,
275
includeArbitraryNames: true
276
})
277
]
278
};
279
```