Skip to content

Use spread syntax to create shallow clones #2310

Closed
@remcohaszing

Description

Initial checklist

Problem

MDX generates JavaScript code that uses shallow copies. The ones I am aware of are defining _components and compiling JSX props. E.g.:

const _components = Object.assign(
  {
    p: 'p',
    pre: 'pre',
    code: 'code'
  },
  props.components
)

IMO it’s cleaner to use spread syntax for shallow clones. E.g.:

const _components = {
  p: 'p',
  pre: 'pre',
  code: 'code',
  ...props.components
}

I have some nitpicky arguments, but mostly I just personally like it better.

  1. Spread syntax exists for shallow clones
  2. Object.assign exists for shallow copying objects from one object to another. It’s still an elegant way to polyfill spread syntax for environments that don’t support it.
  3. MDX generates code with uses default a default argument. Support for this is roughly the same as for spread syntax.
  4. Spread syntax produces a slightly flatter AST.
  5. Terser can minify it better by flattening / inlining / deduping objects.

Solution

Replace Object.assign() with spread syntax.

Alternatives

Keep using Object.assign().

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions