webpack loader for esnext private fields and methods?

Viewed 1663

So i'm new to webpack, and I'm trying to configure it to work with esnext private methods and fields. I haven't specified a loader yet, but i'm not exactly sure which one to use. Currently, my webpack.config.js file looks like this:

const path = require("path");

module.exports = {
    entry: "./src/Rorke.js",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "rorke.js"
    }
};

When i run webpack, it throws an error: Unexpected character '#'

Rorke.js looks like this:

import Sprite from "./Sprite";
const test = new Sprite(0, 0);

and Sprite.js looks like:

export default class Sprite {
    #x;
    #y;
    constructor(x, y) {
        this.#x = x;
        this.#y = y;
    }
}

When i use the regular es6 class without the private fields it works fine, but not with the private fields.

Which loader should i use/how can i fix this?

2 Answers

I solved this problem with a babel plugin called:

@babel/plugin-proposal-private-methods

//babel.config.js
module.exports = {
  presets: [
    [
      "@babel/preset-env",
      {
        targets: { node: "current" },
      },
    ],
    "@babel/preset-typescript",
  ],
  plugins: [
    "@babel/plugin-proposal-private-methods",
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread",
  ],
};

Not an exact answer to your question but may be useful to those who land here.

The problem is that you (or some code you depend on) are using private classes which are not transpiled for old browser support. Check the compatibility here.

Fixed by doing the following:

  1. use BrowserStack to spin up Safari 13
  2. run your app locally
  3. reproduce the error - this is important, you cannot fix what you cannot reproduce
  4. click on the error in the console to inspect the source
  5. remove or update related code. In my case, I had a top-level import of a library that I did not even use.
Related