Skip to content

Mobx class property decorators doesn't work #6571

@mhaidamashko

Description

@mhaidamashko

Describe the bug

I'm trying to migrate from babel to swc,(started from swc for JEST)
I have an old codebase that includes MobX5"mobx": "^5.15.2", with decorators.

To manage decorators I used babel plugins

// ...
 ['@babel/plugin-proposal-decorators', { legacy: true }],
 ['@babel/plugin-proposal-class-properties', { loose: true }],
// ...

full babel plugins list

[
 '@babel/plugin-proposal-optional-chaining',
 '@babel/plugin-proposal-nullish-coalescing-operator',
 '@babel/plugin-syntax-dynamic-import',
 ['@babel/plugin-proposal-decorators', { legacy: true }],
 '@babel/plugin-proposal-export-default-from',
 '@babel/plugin-proposal-export-namespace-from',
  ['@babel/plugin-proposal-class-properties', { loose: true }],
],

How to reproduce an issue(I created a jest test)

import { computed, observable } from 'mobx';

export class OrderLine {
    @observable price = 0;
    @observable amount = 1;

    constructor(price) {
        this.price = price;
    }

    @computed get total() {
        return this.price * this.amount;
    }
}

My test

import { OrderLine } from './OrderLine';

it('check checky', () => {
    const instance = new OrderLine(5);
    expect(instance.price).toEqual(5);
    expect(instance.amount).toEqual(1);
    expect(instance.total).toEqual(5); // it returns NaN but should be 5
});

The last test failed with a NaN(because this.amount is undefined) but should return 5 and pass.

Thanks for your work, it's a very inspiring project.

Input code

No response

Config

{
    "jsc": {
        "parser": {
            "syntax": "ecmascript",
            "jsx": true,
            "numericSeparator": false,
            "classPrivateProperty": false,
            "privateMethod": false,
            "classProperty": false,
            "functionBind": false,
            "optionalChaining": true,
            "dynamicImport": true,
            "nullishCoalescing": true,
            "decorators": true,
            "decoratorsBeforeExport": true,
            "exportDefaultFrom": true,
            "exportNamespaceFrom": true
        },
        "target": "es2022",
        "transform": {
            "legacyDecorator": true,
            "decoratorMetadata": true,
            "react": {
                "runtime": "automatic"
            }
        }
    }
}

Playground link

https://github.com/mhaidamashko/swc-decorators-bug

Expected behavior

I expect to have the same behavior as babel decorators to make it work, maybe we could have the extra option here to manage it.

Actual behavior

No response

Version

1.3.21

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions