Getting an error message with npm and Typescript that says: "Import statement cannot be used outside

After developing and publishing a package to npm, the code snippet below represents how it starts:

import * as aws from "@pulumi/aws";
import * as pulumi from "@pulumi/pulumi";

export interface ...
export class controlplaneDependencies extends pulumi.ComponentResource {
...

The publication and installation processes are successful. However, when attempting to execute the code in a different index.ts, an error occurs:

import * as aws from "@pulumi/aws";
    ^^^^^^
    
    SyntaxError: Cannot use import statement outside a module
        at compileFunction (<anonymous>)
        at Object.compileFunction (node:vm:353:18)
        at wrapSafe (node:internal/modules/cjs/loader:1039:15)
        at Module._compile (node:internal/modules/cjs/loader:1073:27)
        at Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
        at Object.require.extensions.<computed> [as .ts] (/Users/cinto/public-cloud-operator/tests/aws/node_modules/ts-node/src/index.ts:431:14)
        at Module.load (node:internal/modules/cjs/loader:989:32)
        at Function.Module._load (node:internal/modules/cjs/loader:829:14)
        at Module.require (node:internal/modules/cjs/loader:1013:19)
        at require (node:internal/modules/cjs/helpers:93:18)

This is how I am using the package:

import * as controlplane from "@bb/controlplane";

stackOutput=new controlplane.controlplaneDependencies("Install dependencies", {
       Provider: awsProvider,

A solution for this issue is currently unknown. Attempts have been made by adding

"type": "module",
but they were unsuccessful.

Other trials involved:

const aws = require( "@hybrid-cloud/aws" )

However, accessing aws within the interface was not possible.

If you have any ideas or suggestions, they would be greatly appreciated. Below is the content of tsconfig.json:


{
  "compilerOptions": {
    "strict": true,
    "strictPropertyInitialization": false,
    "target": "ES6",
    "module": "CommonJS",
    "moduleResolution": "Node",
    "sourceMap": true,
    "declaration": true,
    "experimentalDecorators": true,
    "pretty": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noImplicitAny": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "lib": [
      "es2019",
      "es5",
      "es6",
      "dom",
      "es2015.collection"
    ],
    "outDir": "./bin"
  },
  "exclude": [
    "node_modules"
  ]
}

Answer №1

After updating my package.json file with the necessary configurations, everything is now working smoothly.

"scripts": {
    "build": "tsc",
    "build:typecheck": "tsc --noEmit",
    "lint:check": "eslint src/**/*.ts",
    "lint:fix": "eslint --fix src/**/*.ts"
  },
  "main": "bin/src/index.js"

I made sure to include es6 in my lib as well. Appreciate all the assistance from everyone!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Encountered a hiccup while trying to install bcrypt

I am having trouble with installing bcrypt through npm on my computer. I keep encountering errors and despite trying to troubleshoot, I have not been successful in resolving the issue. Can someone provide guidance on how to diagnose and fix this problem ...

Guide to effortlessly set up a Node-RED environment with additional nodes using Docker automation

I am looking for a way to automatically deploy a Node-RED instance using docker-compose. The objective is to deploy: Flows (COMPLETED - by populating /data/flows.json) Settings (COMPLETED - by populating /data/settings.js) Login credentials (COMPLETED - ...

Tips for testing nested subscribe methods in Angular unit testing

FunctionToTest() { this.someService.method1().subscribe((response) => { if (response.Success) { this.someService.method2().subscribe((res) => { this.anotherService.method3(); }) } }); } Consider the following scenario. ...

Error thrown when attempting to pass additional argument through Thunk Middleware in Redux Toolkit using TypeScript

I have a question regarding customizing the Middleware provided by Redux Toolkit to include an extra argument. This additional argument is an instance of a Repository. During store configuration, I append this additional argument: export const store = con ...

Encountering an Error When Trying to Run Npm Install in React-Native

I encountered an issue while trying to perform an npm install on my project, so I deleted the node modules folder in order to reinstall it. However, even after running npm install in the appropriate directory, I continued to face numerous errors in my term ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...

The declaration file for the module could not be located as '@types/...@latest' is not available in the npm registry

After installing react-pivottable, I encountered an error when attempting to import it: import PivotTableUI from 'react-pivottable'; The error message in vscode warned: Could not find a declaration file for module 'react-pivottable'. ...

Tips for implementing conditional styling (using else if) in a react component

Currently, while iterating through a list of header names, I am attempting to change the CSS style of a react component based on three different conditions. I have managed to make it work for one condition, but I am facing challenges when trying to impleme ...

Module 'fs.realpath' cannot be located after updating to NPM version 5.0.1

After upgrading npm to v5.0.1 from the previous version 4, I have encountered several catastrophic issues. Currently, I am facing a roadblock where any node.js application I attempt to run completes 'npm install' without errors but throws the fo ...

Diving into the world of npm scripts: Understanding the differences between "clean:dist" and "clean"

I'm currently trying to understand the purpose of "clean:dist" or "clean:js" compared to just "clean" within the package.json scripts section. Despite searching online and consulting the NPM documentation, I haven't been able to find a clear answ ...

Enhancing current interfaces

I'm exploring Koa and the module system in Node.js. Although I'm not asking about a specific koa question, all the code I'm working with involves using koa. In Koa, every request is defined by the Request interface: declare module "koa" { ...

What is the proper way to utilize setTimeout in TypeScript?

Let's take a look at an example of how to use setTimeout in Angular and TypeScript: let timer: number = setTimeout(() => { }, 2000); However, upon compilation, you may encounter the following error message: Error TS2322: Type 'Timeout' ...

Troubleshooting material-ui issues in Webpack

I'm currently in the process of cloning my friend's repository on GitHub. If you're interested, here is the link to the repo: https://github.com/feijihn/todolist_react The web app is developed using node.js, react.js, and material.ui. Aft ...

What is the best way to specify parameter names and types for a TypeScript function that can take either one or two arguments?

Looking to create a function with two different calling options: function visit(url: string, options: Partial<VisitOptions>): void function visit(options: Partial<VisitOptions> & {url:string}): void I'm exploring the most effective w ...

What is the best method for expanding nodes after the tree has been loaded?

Greetings! I am currently working on a web application using Angular 5. One of the features I have implemented is loading trees onto my webpage. These trees are populated with data from an API and are designed to be dynamic. After loading the tree, my goal ...

Troubleshooting: The issue of importing Angular 2 service in @NgModule

In my Angular 2 application, I have created an ExchangeService class that is decorated with @Injectable. This service is included in the main module of my application: @NgModule({ imports: [ BrowserModule, HttpModule, FormsModu ...

Remove httpOnly cookies in Express

Can browser cookies with the attribute HttpOnly:true be deleted? Here is a snippet of my login endpoint: async login(@Ip() ipAddress, @Request() req, @Res() res: Response) { const auth = await this.basicAuthService.login(req.user, ipAddress); ...

Issue: Unable to locate 'child_process' in Angular 5

I am a newcomer to Angular, and I have encountered a requirement in my project to retrieve the MAC address of the user's system. To achieve this, I performed an NPM installation as shown below: npm install --save macaddress Next, I added the follow ...

Nestjs opts to handle invalid routes by throwing a NotFoundException rather than a MethodNotAllowed

I've recently developed a Rest API using NestJS and now I'm focusing on customizing error responses. Specifically, I want to address the scenario where a user calls an endpoint with the incorrect HTTP method. Take for instance the endpoint GET / ...

Enhancing the NextPage Typescript Type: A Step-by-Step Guide

I'm working on a NextJS dashboard with role-based access control and I need to pass an auth object to each page from the default export. Here's an image showing an example of code for the Student Dashboard Home Page: Code Example of Student Dashb ...