Skip to content Skip to sidebar Skip to footer

Making Export Default Work With Babel, Webpack And Node.js

I can't figure out why my code doesn't work. I am building a ES6 style class and want to export it to be able to use it somewhere else in the server side. I put the code into a fi

Solution 1:

Webpack is a bundler for producing packages that run on the client (in the browser), it is not aware of or concerned with code on the server. (Unless you are doing universal application stuff.)

You will notice too that your npm dev script is simply asking node to load the server.js file, which is (correctly) not mentioned anywhere in your Webpack config.

You are looking for babel-register:

One of the ways you can use Babel is through the require hook. The require hook will bind itself to node’s require and automatically compile files on the fly.

Create an "entry" file that first requires babel-register and then requires your server.js file:

// server-entry.jsrequire('babel-register')
require('./server.js')

Now change your npm dev script to be node server-entry.js.

______

Aside: it is necessary to create an entry file as babel-register cannot transpile the file in which it is invoked. For example, this would fail:

// server.jsrequire('babel-register')

exportdefaultfunction () {}

Post a Comment for "Making Export Default Work With Babel, Webpack And Node.js"