RedGiant RedGiant - 3 months ago 13
Javascript Question

Passing getChildContext() to reactjs higher order components throws unexpected token error in webpack

I got the following example from HERE to make a higher order component for passing context reliably.

However, there is a

Unexpected token
error passing
getChildContext()
function when compiling the script using webpack:

getChildContext = () => getChildContext(this.props);
^^^


Code:

const provideContext =
(childContextTypes, getChildContext) => (Component) => {
class ContextProvider extends React.Component {
getChildContext = () => getChildContext(this.props);

render() {
return <Component {...this.props} />;
}
}
ContextProvide.childContextTypes = childContextTypes;

return ContextProvider;
};


Is there a workaround way of passing the function?

My webpack config:

var common = {
output: {path: BUILD_DIR},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
include: APP_DIR,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
},
{
test: /\.(png|jpg)$/,
loader: 'file-loader'
}
]
},
resolve: {
alias: {
'react': path.join(__dirname, 'node_modules', 'react'),
'react-dom': path.join(__dirname, 'node_modules', 'react-dom')
},
extensions: ['', '.js']
},

};


config.push(
merge(common, {
entry: {
ItemPage:APP_DIR+'/page/'+fileName+'.js',

},
devtool: 'source-map',
output: {
filename: "[name].js",
libraryTarget: 'umd',
library: "[name]"
},
externals: [{
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',

},
"react-dom": "ReactDOM"
}]

})
);

module.exports = config;

QoP QoP
Answer

You are getting Unexpected token because you are missing one babel plugin, transform-class-properties which is included in stage-1 preset

With stage-1, it works

Without stage-1, it does not work

So in order to fix it, you have to

1º Install stage-1

npm install --save-dev babel-preset-stage-1

2º Add it to .babelrc

{
  "presets": ["react","es2015","stage-1"]
}

Or to the webpack config

query: {
       presets: ["react","es2015","stage-1"]
}