|
| 1 | +# 引用 JSON 文件 |
| 2 | + |
| 3 | +Rslib 支持在代码中引用 JSON 文件。 |
| 4 | + |
| 5 | +## JSON 文件 |
| 6 | + |
| 7 | +你可以直接在 JavaScript 文件中引用 JSON 文件。 |
| 8 | + |
| 9 | +### 默认引用 |
| 10 | + |
| 11 | +```json title="example.json" |
| 12 | +{ |
| 13 | + "name": "foo", |
| 14 | + "items": [1, 2] |
| 15 | +} |
| 16 | +``` |
| 17 | + |
| 18 | +```js title="index.js" |
| 19 | +import example from './example.json'; |
| 20 | + |
| 21 | +console.log(example.name); // 'foo'; |
| 22 | +console.log(example.items); // [1, 2]; |
| 23 | +``` |
| 24 | + |
| 25 | +:::warning |
| 26 | + |
| 27 | +在 Bundle 模式下,JSON 文件支持默认引用和具名引用。 |
| 28 | + |
| 29 | +在 Bundleless 模式下,JSON 文件仅支持具名引用。 |
| 30 | + |
| 31 | +::: |
| 32 | + |
| 33 | + |
| 34 | +### 具名引用 |
| 35 | + |
| 36 | +Rslib 同样支持通过 named import 来引用 JSON 文件: |
| 37 | + |
| 38 | +下面是一个使用示例,假设源码如下: |
| 39 | + |
| 40 | +import { Tabs, Tab } from '@theme'; |
| 41 | + |
| 42 | +<Tabs> |
| 43 | + <Tab label="src/index.ts"> |
| 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 | +```json title="example.json" |
| 53 | +{ |
| 54 | + "name": "foo", |
| 55 | + "items": [1, 2] |
| 56 | +} |
| 57 | +``` |
| 58 | + </Tab> |
| 59 | +</Tabs> |
| 60 | + |
| 61 | +会根据配置文件中的 [产物结构](/guide/basic/output-structure) 配置,打包出如下产物: |
| 62 | + |
| 63 | +<Tabs> |
| 64 | +<Tab label="Bundle"> |
| 65 | +<Tabs> |
| 66 | + <Tab label="dist/index.js"> |
| 67 | +```tsx |
| 68 | +var example_namespaceObject = { |
| 69 | + "name": "foo" |
| 70 | +}; |
| 71 | +console.log(example_namespaceObject.name); |
| 72 | +``` |
| 73 | + |
| 74 | + </Tab> |
| 75 | +</Tabs> |
| 76 | +</Tab> |
| 77 | + |
| 78 | +<Tab label="Bundleless"> |
| 79 | + |
| 80 | +<Tabs> |
| 81 | + <Tab label="dist/index.js"> |
| 82 | + |
| 83 | +```tsx |
| 84 | +import * as example from './example.js'; |
| 85 | + |
| 86 | +console.log(example.name); |
| 87 | +``` |
| 88 | + |
| 89 | + </Tab> |
| 90 | + <Tab label="dist/example.js"> |
| 91 | +```tsx |
| 92 | +var example_namespaceObject = JSON.parse('{"name":"foo","items":[1,2]}'); |
| 93 | +var __webpack_exports__items = example_namespaceObject.items; |
| 94 | +var __webpack_exports__name = example_namespaceObject.name; |
| 95 | +export { __webpack_exports__items as items, __webpack_exports__name as name }; |
| 96 | +``` |
| 97 | + </Tab> |
| 98 | +</Tabs> |
| 99 | +</Tab> |
| 100 | + |
| 101 | +</Tabs> |
0 commit comments