Christopher Francisco
Christopher Francisco

Reputation: 16278

How to build a ES6 express app with webpack 2 and babel?

Given the following Webpack 2 configuration, I want to write a express app using ES6. My .babelrc has only the es2015 preset:

const path = require('path');

module.exports = {
  target: 'node',

  entry: path.resolve(__dirname, 'src', 'server.js'),

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'server.bundle.js',
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader',
      },
    ],
  },
};

Running webpack and starting the server work fine, but when accessing the URL through the browser I get the following error:

Error: Cannot find module "."
    at webpackMissingModule (/Users/Me/project/dist/server.bundle.js:18208:74)

I don't know whether it's due to the . in a require('./some/other/file') call (not all files are ES6, so these one use require() instead of import); or maybe some configuration I'm missing.

And also, given that stack trace I can't really map it to the original source file.

Thanks in advance

Update 1

I just realize I'm trying to use webpack to transpile ES6 code because I'm trying to replicate another build task (the one in mern.io), but I could do the same just with babel. Maybe there's no reason for using webpack on the serverside.

Upvotes: 0

Views: 1269

Answers (2)

Vadym Petryshyn
Vadym Petryshyn

Reputation: 175

You need to install and add in webpack.config.js ExternalsPlugin:

plugins: [
    new ExternalsPlugin({
        type: 'commonjs',
        include: path.join(__dirname, './node_modules/'),
    }),
],

It helped me, I hope you too, because I spent a lot of time for solutions this problem)

Upvotes: 1

the_bluescreen
the_bluescreen

Reputation: 3414

Maybe the reason is that you are using target: "node" on webpack config. So that means it's creating your package for nodejs environment. Can you test after changing it to target: "web" for client transpile?

https://webpack.js.org/concepts/targets/

Upvotes: 0

Related Questions