Skip to content

Parse and modify top-level declarations in a module #68

@Lms24

Description

@Lms24

Describe the feature

I'd like to be able to modify top-level declarations within a module to, for example, modify objects that are exported in a separate statement. Something like:

// currently, there's no magicast-native way of accessing this declaration
const myConfig = defineConfig({/*...*/})
export default myConfig;

I'm using magicast in a script that's supposed to modify a user's vite.config.js and this quite common way of specifying a vite config unfortunately causes problems.

API proposal:

I'm thinking about something along these lines:

const originalCode = `
  const myConfig = defineConfig({/*...*/})
  export default myConfig;
`

const mod = parseModule(originalCode);

// example modification
mod.$declarations.myConfig = builders.raw(...)

Once we have a way of accessing/modifying declarations, we could for example adjust theaddVitePlugin helper to use the $declarations field to adjust the config object if it is not directly default-exported.

I'm happy to give this a try to implement but I'd like to hear your thoughts around this first.

This is somewhat related to #45 but I believe modifying/parsing existing declarations isn't discussed in this issue.

Limitations

I think we need to accept that we couldn't possibly handle all kinds of declarations or complex syntax within them but for starters, I believe handling object declarations or function calls (like defineConfig) might be enough.

Additional information

  • Would you be willing to help implement this feature?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions