0

I'm new to "ES7" decorators (by which I really mean decorators enabled by the Babel babel-plugin-transform-decorators-legacy plug-in that was originally based on the ES7 decorator proposal), and I'm having a little trouble with how they work. I understand that a method decorator modifies the method, but I'm unclear what "side effects" can happen in the process. Specifically I'd like to know if a decorator can generate an export, ie. can I make a decorator like this:

class Foo {
    @export
    bar() { doSomething(); }
}

which generates:

export const bar = Foo.prototype.bar;
// or
export const bar = new (Foo()).bar;

or alternatively:

class Foo {
    @export
    static bar() { doSomething(); }
}

to:

export const bar = Foo.bar;

In short, can a decorator ever create an export statement?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
machineghost
  • 33,529
  • 30
  • 159
  • 234
  • Exports should be declared at the top of a module so that they are statically analysable. So even if you _could_ (it would probably require some hacky plugin for a transpiler, e.g Babel), you really shouldn't. – sdgluck Sep 26 '16 at 18:05
  • 1
    Why do you want to export a method at all? – Bergi Sep 26 '16 at 18:07
  • A module might expose something as if it were a static function, but (behind the scenes) it might make more sense to implement that function as a method of a (singleton) object. – machineghost Sep 27 '16 at 19:44

1 Answers1

2

No, export declarations cannot be created dynamically. At best, you could dynamically create a module file that contains them.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375