reactjsecmascript-6webpacktraceur

ES6(traceur) + Webpack + React


Is it possible to develop React component in ES6?

For example:

import MyWdiget from './MyWidget';

React.render(<MyWidget />, mountNode);

also be able to use ES6 to define component:

class MyWidget extends ReactComponent {

    render() {
        <h3>Hello from Widget</h3>
    }
}

And somehow build all that using webpack? How would webpack config file look like?

I managed to compile ES6 code using traceur and webpack, but cannot transform JSX to javascript and also extend class using ES6.

Thx


Solution

  • Using ES6 with React is partially possible with the 6to5 transpiler. Writing React components as ES6 classes need some work in the framework. However, JSX and other nifty ES6 features can be transpiled in Webpack. Here's an example partial configuration:

    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loaders: [ '6to5?experimental=true&runtime=true' ] },
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            to5Runtime: "imports?global=>{}!exports-loader?global.to5Runtime!6to5/runtime"
        })
    ]
    

    The module loader is able to process JSX by enabling the experimental option. The other option, runtime, is to disable injection of a small runtime on a per file basis. Instead, a global one will be provided, as is stated in the plugin configuration.