Consuming pure ES2015 libraries with Webpack 2

218 Views Asked by At

Context

I've been using a monolithic src tree internally and have recently split it into separate smaller libraries for reuse. Since this is all internal, I have no need for these libraries to produce ES5. I want our webpack 2 apps to be able to consume pure ES2015 libraries.

Problem

The problem is, when I produce a pure ES2015 library, my webpack transpiled app fails with:

Uncaught TypeError: Class constructor RouteConfig cannot be invoked without 'new'

The source of this is:

import {RouteConfig} from '@acme/ui/config'

Sanity check

For verification that I'm not doing anything obviously wrong, I verified:

  1. the library built as ES5 works
  2. the app including the library (with the ES2015 preset added to it) via source alias works

Details

Library .babelrc

{ // produce a pure es2015 build
  "presets": [
    "es2017",
    "es2016",
    "stage-0",
    "react"
  ],
  "plugins": [
    "babel-relay-plugin-loader",
    "flow-react-proptypes",
    "transform-flow-strip-types",
    "lodash",
    "transform-runtime"
  ],
  "env": {
    "production": {
      "presets": [
        "react-optimize"
      ],
      "plugins": [
        ["react-remove-properties", {"properties": ["data-test"]}]
      ]
    }
  }
}

Application .babelrc:

{
  "presets": [
    "es2017",
    "es2016",
    ["es2015", {"modules": false}], // allows webpack2 to interpret ES2015 modules+
    "stage-0", // if omitted, this leaves `export Log from './Log'`
    "react"
  ],
  "plugins": [
    "babel-relay-plugin-loader",
    "flow-react-proptypes",
    "transform-flow-strip-types",
    "lodash",
    "transform-runtime",
    "react-hot-loader/babel"
  ],
  "env": {
    "production": {
      "presets": [
        "react-optimize"
      ],
      "plugins": [
        ["react-remove-properties", {"properties": ["data-test"]}]
      ]
    }
  }
}

TLDR;

  • We have many libraries and many apps that are internal and don't need ES5
  • I want to author both a library and an app in ES2015+.
  • Each library will create a pure ES2015 build for the private npm package.
  • I want to take advantage of as much webpack 2 tree shaking/optimization as possible.
  • Our library works as an ES5 package
  • Our library works as a source alias to the app with the 2015 preset added to it's .babelrc
  • Source alias usage for all our libraries is not desirable

Question

What config is needed to get webpack 2 to consume a pure ES2015 library?

1

There are 1 best solutions below

0
On

It's possible you're excluding the node_modules folder in your babel-loader. If so, you can try modifying the exclude regex.

ie.

test: /\.js$/,
use: [
    'babel-loader'
],
exclude: [/.*node_modules((?!folder_name_here).)*$/]