Search code examples
javascriptwebpackjavascript-objects

Private fields not compiling with Webpack


I am trying to create a private field for my class, but for some reason, webpack refuses to compile it, it keeps giving me an error, here's an example

class Example {
  #privateField;

  constructor() {...}
}

here's the error this Example produces

ERROR in ./src/example.js 2:2
Module parse failed: Unexpected character '#' (2:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| class Example {
>   #privateField;
|
|   constructor() {
 @ ./src/example.js
 @ ./src/index.js

Solution

  • Webpack, on it's own is just a Javascript bundler, if you have modern JS features, webpack will not understand this,.

    Luckily, babel and webpack work well together, so to get ESNext features, you will want to include the babelLoader..

    https://webpack.js.org/loaders/babel-loader/