|
| 1 | +# Import JSON files |
| 2 | + |
| 3 | +Rslib supports import JSON files in code. |
| 4 | + |
| 5 | +## JSON file |
| 6 | + |
| 7 | +You can directly import JSON files in JavaScript files. |
| 8 | + |
| 9 | +:::warning |
| 10 | + |
| 11 | +In bundle mode, JSON files support both default and named import. |
| 12 | + |
| 13 | +In bundleless mode, JSON files only support named import. |
| 14 | + |
| 15 | +::: |
| 16 | + |
| 17 | +### Default import |
| 18 | + |
| 19 | +```json title="example.json" |
| 20 | +{ |
| 21 | + "name": "foo", |
| 22 | + "items": [1, 2] |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +```js title="index.js" |
| 27 | +import example from './example.json'; |
| 28 | + |
| 29 | +console.log(example.name); // 'foo'; |
| 30 | +console.log(example.items); // [1, 2]; |
| 31 | +``` |
| 32 | + |
| 33 | +### Named import |
| 34 | + |
| 35 | +Rslib also supports importing JSON files through named import. |
| 36 | + |
| 37 | +Here is an example, assuming the source code is as follows: |
| 38 | + |
| 39 | +import { Tabs, Tab } from '@theme'; |
| 40 | + |
| 41 | +<Tabs> |
| 42 | + <Tab label="src/index.ts"> |
| 43 | + |
| 44 | +```js |
| 45 | +import { name } from './example.json'; |
| 46 | + |
| 47 | +console.log(name); // 'foo'; |
| 48 | +``` |
| 49 | + |
| 50 | + </Tab> |
| 51 | + <Tab label="src/example.json"> |
| 52 | + |
| 53 | +```json |
| 54 | +{ |
| 55 | + "name": "foo", |
| 56 | + "items": [1, 2] |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | + </Tab> |
| 61 | +</Tabs> |
| 62 | + |
| 63 | +Based on the configuration in the [output structure](/guide/basic/output-structure) specified in the configuration file, the following outputs will be emitted: |
| 64 | + |
| 65 | +<Tabs> |
| 66 | +<Tab label="bundle"> |
| 67 | +<Tabs> |
| 68 | + <Tab label="dist/index.js"> |
| 69 | + |
| 70 | +```tsx |
| 71 | +var example_namespaceObject = { |
| 72 | + u: 'foo', |
| 73 | +}; |
| 74 | +console.log(example_namespaceObject.u); |
| 75 | +``` |
| 76 | + |
| 77 | + </Tab> |
| 78 | +</Tabs> |
| 79 | +</Tab> |
| 80 | + |
| 81 | +<Tab label="bundleless"> |
| 82 | + |
| 83 | +<Tabs> |
| 84 | + <Tab label="dist/index.js"> |
| 85 | + |
| 86 | +```tsx |
| 87 | +import * as example from './example.js'; |
| 88 | + |
| 89 | +console.log(example.name); |
| 90 | +``` |
| 91 | + |
| 92 | + </Tab> |
| 93 | + <Tab label="dist/example.js"> |
| 94 | + |
| 95 | +```tsx |
| 96 | +var example_namespaceObject = JSON.parse('{"name":"foo","items":[1,2]}'); |
| 97 | +var __webpack_exports__items = example_namespaceObject.items; |
| 98 | +var __webpack_exports__name = example_namespaceObject.name; |
| 99 | +export { __webpack_exports__items as items, __webpack_exports__name as name }; |
| 100 | +``` |
| 101 | + |
| 102 | + </Tab> |
| 103 | +</Tabs> |
| 104 | +</Tab> |
| 105 | + |
| 106 | +</Tabs> |
0 commit comments