How to build app with MobX annotations via webpack using Babel 6

I was searching for hints how to build games based on React. There is nice simple react-game-kit. The kit contains demo where you can as a player discover the kit itself.

Just type:

git clone git@github.com:FormidableLabs/react-game-kit.git
cd react-game-kit
npm install
npm start

Then you can open the demo in your browser: http://localhost:3000/

react-game-kit-demo

I was trying to build my own game based on code from react-game-kit. I hit one problem that webpack was not able to process MobX annotation @observable in GameStore.

Module build failed: SyntaxError: Unexpected token (4:2)

  2 | 
  3 | class GameStore {
> 4 |   @observable characterPosition = { x: 0, y: 0 };
    |   ^

The problem is described in MobX documentation. The annotation @observable is available only in ES7 which is fairly new. In case of Babel 5 or 6 you should use “Stage 0” processing.

Here is how to fix the problem:

npm install babel-plugin-transform-decorators-legacy --save-dev
npm install babel-preset-stage-0 --save-dev

The first package “transform-decorators-legacy” allows you to use decorators with Babel 6. The second package allows you to enable plugins in Stage 0 of build by Babel.

Then you need to tell webpack to use the plugin for decorators transform. Add list of plugins to query section of webpack.config.js:

...
  query: {
    presets: ['es2015', 'react'],
    plugins: ['transform-decorators-legacy', 'transform-class-properties']
  }
...

Now you can start the webpack and @observable will be processed.

If you want to learn more about MobX, there is nice tutorial at Egghead.io.

26. December 2016 at 16:38 - Software engineering (Tags: , , , ). Both comments and pings are currently closed.

Comments are closed.