Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack loader for esnext private fields and methods?

Tags:

webpack

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?

like image 565
dwib Avatar asked Jan 26 '23 16:01

dwib


1 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",
  ],
};
like image 75
MonkBen Avatar answered Jan 28 '23 05:01

MonkBen