Skip to content

Commit 51a82eb

Browse files
committed
docs: update usage
1 parent 69536e6 commit 51a82eb

File tree

1 file changed

+41
-4
lines changed

1 file changed

+41
-4
lines changed

README.md

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,9 @@ Code to modify and append `b` to `foo` prop of defaultExport:
5151
```js
5252
import { loadFile, writeFile } from "magicast";
5353

54-
const _module = await loadFile("config.js");
54+
const mod = await loadFile("config.js");
5555

56-
_module.exports.default.props.foo.push("b");
56+
mod.exports.default.foo.push("b");
5757

5858
await writeFile(_module);
5959
```
@@ -72,15 +72,52 @@ export default {
7272
import { parseCode, generateCode } from "magicast";
7373

7474
// Parse to AST
75-
const _module = parseCode(`export default { foo: ['a'] }`);
75+
const mod = parseCode(`export default { }`);
7676

77+
// Ensure foo is an array
78+
mod.exports.default.foo ||= [];
7779
// Add a new array member
78-
_module.exports.default.props.foo.push("b");
80+
mod.exports.default.foo.push("b");
81+
mod.exports.default.foo.unshift("a");
7982

8083
// Generate code
8184
const { code, map } = generateCode(_module);
8285
```
8386

87+
Generated code:
88+
89+
```js
90+
export default {
91+
foo: ["a", "b"],
92+
};
93+
```
94+
95+
**Example:** Get the AST directly:
96+
97+
```js
98+
import { parseCode, generateCode } from "magicast";
99+
100+
const mod = parseCode(`export default { }`);
101+
102+
const ast = mod.exports.default.$ast
103+
// do something with ast
104+
```
105+
106+
**Example:** Function parameters:
107+
108+
```js
109+
import { parseCode, generateCode } from "magicast";
110+
111+
const mod = parseCode(`export default defineConfig({ foo: 'bar' })`);
112+
113+
// Support for both bare object export and `defineConfig` wrapper
114+
const options = mod.exports.default.$type === 'function-call'
115+
? mod.exports.default.arguments[0]
116+
: mod.exports.default;
117+
118+
console.log(options.foo) // bar
119+
```
120+
84121
## Development
85122

86123
- Clone this repository

0 commit comments

Comments
 (0)