1

I get an "Unexpected identifier" error when I try to import a class.

I'm importing class this way:

Class to be exported (WindowManager)

export default class WindowManager {
    sayHello() {
        console.log('hello')
    }
}

Class which imports (Main)

import WindowManager from './handlers/WindowManager';

WindowManager = new WindowManager();
WindowManager.sayHello()

Folder hierarchy

Class which imports (Main) > handlers > Class to be imported (WindowManager)

Extra info

Throws the error at this line of code (Main)

import WindowManager from './handlers/WindowManager.js';

I've looked into Unexpected Identifier {classname} when importing JavaScript Class into another Class and make changes and still nothing

chazsolo
  • 7,873
  • 1
  • 20
  • 44
  • Are you sure it’s being thrown by the import? Th line that looks. suspect to me is WindowManager = new WindowManager.” I don’t think you can instantiate an object from a class like that and it makes sense it would cause that error. It should be something like “WindoManager myManager = new WindowManager”. – C. Peck Mar 27 '19 at 15:54
  • @C.Peck Yep, I'm sure. I tried your syntax and its invalid... changed my declaration from `WindowManager = new WindowManager();` to `const windowManager = new WindowManager();` and I still get the same error – leandrojesus-programmer Mar 27 '19 at 16:01

1 Answers1

0

I was able to fix this by migrating to TypeScript.

What is TypeScript?

TypeScript is JavaScript on steroids, basically. It adds types, private methods, etc. Also provides a compiler which compiles your TypeScript code into JavaScript code! So you don't have to worry about compatibilty, you write on TypeScript and then compile to JavaScript with a simple command.

How to install TypeScript?

npm install -g typescript

How to use TypeScript?

  • Enter your project folder (where package.json is);

  • Generate tsconfig.json by running tsc --init;

  • Create your TypeScript index file;

  • Run tsc on terminal to compile ALL TypeScript project files to JavaScript;

  • Notice that your index TypeScript file was compiled to JavaScript;

  • Use the compiled JavaScript file as the main entry point on package.json;
  • Start your app/website/whatever heheh.

Notes:

  • Everytime you make changes to TypeScript file you have to use tsc to recompile the code and make the changes on the JavaScript file;

  • VS Code comes with TypeScript support, if you're using Atom you can install TypeScript package by following this tutorial: Installing atom-typescript package.

Happy coding!

Articles that helped me: