How to transpile a node_module with webpack in a web worker?

I am trying to include a node module (primitive-ellipsoid) in my wepback project. The module is not transpiled to es5 so throws an error when used in the browser:

Uncaught Error: Module parse failed: /Users/kevzettler/code/crashgiants/node_modules/primitive-ellipsoid/index.js Unexpected token (8:4)
You may need an appropriate loader to handle this file type.
|   // Default to an oblate spheroid
|   const { latSegments = 32, lngSegments = 64, rx = 2, ry = 1, rz = 1 } = {
|     ...options
|   };
|

This project is an older create-react-app webpack that is ejected.

    "webpack": "3.5.1",
    "webpack-dev-server": "2.8.2",
    "webpack-manifest-plugin": "1.2.1",

It is using babel and babel-loader and worker-loader I have a webpack.config.dev.js with rules like:

    rules: [
      {
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
          // Process JS with Babel.
          {
            test: /.(js|jsx)$/,
            include: [
              paths.appSrc,
            ],
            exclude: /.worker.js$/,
            loader: require.resolve('babel-loader'),
            options: {
              // This is a feature of `babel-loader` for webpack (not Babel itself).
              // It enables caching results in ./node_modules/.cache/babel-loader/
              // directory for faster rebuilds.
              //cacheDirectory: true,
            },
          },

          {
            test: /.worker.js$/,
            exclude: /node_modules/,
            use: [
              'worker-loader',
              require.resolve('babel-loader'),
            ]
          }
        ]

I have babel configured in package.json with:

  "babel": {
    "plugins": [
      "babel-plugin-transform-decorators-legacy"
    ],
    "presets": [
      [
        "env",
        {
          "targets": "defaults"
        }
      ],
      "flow",
      "react-app"
    ]
  },

I have tried messing around with includes and excludes in the webpack.config.json to no success. I am confused if I need to focus on the worker-loader rule because it also uses the babel-loader or if the top level babel-loader gets applied as well.

Source: Ask Javascript Questions

LEAVE A COMMENT