Home > Mobile >  "Cannot use import statement outside of module" - JavaScript module imported into TypeScri
"Cannot use import statement outside of module" - JavaScript module imported into TypeScri

Time:12-10

To further explain, it can be imagined that I have a set of JavaScript modules that are triggered from one initial module, which is imported into an Angular component.

What I have tried:

I am using "type" : "module" in the package.json file and have declared all scripts as modules in a typings file, I have also declared them under scripts in angular.json. I went as far as settings the scripts as modules in index.html, but I still receive the "Uncaught SyntaxError: Cannot use import statement outside a module".

When the error occurs:

The error comes from the first import statement from within the initial JavaScript module, e.g., line 1.

The import statement simply looks like this from within the initial JavaScript module, with subsequent statements to other scripts, all of which will trigger the same problem.

import * as objParser from './scripts/objParser.js'

I can confirm that the issue is not the code logic, since the code does actually work in development mode, but of course, I am unable to run this as a production package.

Maybe the issue?

My idea is that Angular is not validating these JavaScript files as modules since they do not use import within the Angular code base. Any Ideas?

CodePudding user response:

use const objParser = require('./scripts/objParser.js');.

CodePudding user response:

You can create an index.ts file in your scripts folder which will allow you to import all modules from that file.

you add them to the index.ts like

export * from './scripts/objParser.js';

then you could import like

import { ObjParser } from './scripts'

if it's not compatible it could be because they aren't typescript libraries.

  • Related