0

I am getting this error when I try to use private fields in an Angular Project.

Error: ./src/app/_helpers/sample.js 6:11
Module parse failed: Unexpected character '#' (6:11)
File was processed with these loaders:

./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
./node_modules/@ngtools/webpack/src/ivy/index.js
./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.

sample.js file:

class Sample {

constructor() {
   this.#reloadConfig(); // 6th line
}

#reloadConfig() {
}

EDIT: Was able to resolve it by upgrading Angular from 11 to 12, seems Angular 11 doesn’t support private methods declared in a JS file.

  • Can you confirm which version of Angular and TypeScript that you are using. – Robin Webb May 18 '22 at 08:23
  • Angular 11 and typeScript 4.1.4 but this is a JS file – Vishal Sharma May 18 '22 at 11:20
  • You're using vanilla JavaScript in an Angular project (Angular CLI?) even though Angular is designed to transpile TypeScript into JavaScript? Are you getting this error during the Angular build or in your browser? Have you checked that your browser and version supports private class fields ? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields#browser_compatibility or https://caniuse.com/mdn-javascript_classes_private_class_fields – Robin Webb May 18 '22 at 11:53
  • I'm getting this error during build itself. – Vishal Sharma May 19 '22 at 12:28
  • Can you create a minimal working example in https://stackblitz.com/? – Robin Webb May 19 '22 at 12:52
  • Was able to resolve this issue by upgrading Angular version from 11 to 12, thanks a lot for your help guys. It seems Angular 11 doesn’t support private methods. – Vishal Sharma May 25 '22 at 14:30

1 Answers1

-1

You just need to use private keyword and remove the #

class Sample {
   constructor() {
      this.reloadConfig();
   }

   private reloadConfig() {
   }
}

TypeScript’s private-declared properties work with all targets — even ECMAScript 3! — Microsoft DevBlog

A.Amayreh
  • 120
  • 1
  • 4
  • 1
    As of TypeScript 3.8+ private fields is supported in TypeScript/Angular. This issue is between compile time accessibility and run time accessibility of members https://stackoverflow.com/questions/59641564/what-are-the-differences-between-the-private-keyword-and-private-fields-in-types – Robin Webb May 18 '22 at 08:30
  • 1
    But this is a JS file not TS, also private works for only compile-time not the run-time. – Vishal Sharma May 18 '22 at 11:22