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

State in Angular stubbornly refuses to switch despite condition changes

Here is the Typescript code, followed by the HTML: public verifySelection() { let choice = false; if (typeof this.formUser.permissionsTemplateID === undefined) { choice = true; } return choice; } <div class="form-group" ...

Ways to avoid route change triggered by an asynchronous function

Within my Next.js application, I have a function for uploading files that includes the then and catch functions. export const uploadDocument = async (url: UploadURLs, file: File) => { const formData = new FormData(); formData.append("file" ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...

`The utilization of a collective interface/data type within an Angular application`

I created a HeaderComponent that requires an object with the structure of {title: string, short_desc: string} as its input property. @Component({ selector: 'header', templateUrl: './header.component.html', styleUrls: ['./hea ...

Working with Grunt in VS Code: Running Grunt tasks from the node_modules.bin

I've been experimenting with Visual Studio Code, Node.js, and Grunt, but I'm running into some issues. It appears that VS Code is not able to execute grunt from the local node_modules\.bin directory where npm installs it. While everything wo ...

The command 'create-react-app' is not valid and cannot be recognized as an internal or external command, operable program, or batch file

I've been struggling to set up a React project, as the create-react-app my-app command doesn't seem to be working. Can anyone offer some assistance? Here are the commands I'm using: npm install -g create-react-app create-react-app my-app ...

Guide on extracting the id from the path parameter in an HTTP request using Cloud Functions and nodejs

I am currently in the process of developing a serverless application using GCP Cloud Functions (nodejs). I have successfully implemented different behaviors based on the request method, but I am facing an issue with retrieving the id from the path paramete ...

What are some ways to utilize .styl stylesheets instead of traditional .css files?

I really hope this isn't a silly question, but I've been searching Google and forums for 30 minutes and can't find anything. I downloaded this npm package (ag-grid) and all their documentation talks about .css files, but the package only ha ...

The addition operator cannot be used with the Number type and the value of 1

Encountering an issue where the operator '+' cannot be applied to types 'Number' and '1' buildQuerySpec() { return { PageSize: this.paging.PageCount, CurrentPage: this.paging.PageIndex + 1, MaxSize: '' ...

npm installation for phonegap failed due to shasum check discrepancy

I've attempted numerous times, but I keep encountering this error (shasum check failed) 4784 error Error: shasum check failed for C:\Users\FENGXI~1\AppData\Local\Temp\npm-7004-QbpFFte5\1387269030233-0.28223602287471 ...

Issue with Npm EACCESS error encountered while attempting to set up Firebase

After switching to a new m1 MacBook Pro, I encountered issues when trying to run and deploy my code using Firebase. When I attempted to deploy my code with the command firebase deploy, I received an error message stating zsh: command not found: firebase. T ...

Combining react-datetime with setInterval in a React application

I'm currently utilizing the react-datetime control from the npm package: click here. How can I set an interval in the time picker? For instance, I want it to display times at intervals of 5 minutes (0, 5, 10, 15, etc.). How can I make this happen? Th ...

What do you need to know about the error message "Module build failed (file-loader)"

Every time I try running my ReactJS project with npm start, I encounter an error for each svg file in the images folder. Can someone help me figure out what mistake I might be making? Thank you in advance. ...

Error encountered: The input value does not correspond to any valid input type for the specified field in Prisma -Seed

When trying to run the seed command tsx prisma/seed.ts, it failed to create a post and returned an error. → 6 await prisma.habit.create( Validation failed for the query: Unable to match input value to any allowed input type for the field. Parse erro ...

Can you provide instructions on how to use RXJS Observables to conduct a service poll?

If I want the get request to "api/foobar" to repeat every 500 milliseconds, how can I modify the code provided below? import {Observable} from "RxJS/Rx"; import {Injectable} from "@angular/core"; import {Http} from "@angular/http"; @Injectable() export ...

Reactive Programming: Transforming an earlier value as it moves down the pipeline

In a recent project, I encountered an interesting scenario involving the execution of multiple requests in a pipe chain. This specific case revolves around the display of images within the quill text editor. The backend returns the content in the followin ...

What is Homebrew's method for handling dependencies?

Can Homebrew and other package managers effectively handle dependencies, including unique scenarios like circular dependencies? Is there a specific pattern, algorithm, or data structure commonly used for this purpose? ...

The addition operator is not compatible with the given types

Hello, I am currently working on integrating PayPal into an Angular 5 project. The code snippet below shows how I render PayPal buttons using a function: ngAfterViewChecked(): void { if (!this.addScript) { this.addPaypalScript().then(() => { ...

Using additional packages in React Native can result in increased memory usage within the project

Wondering about adding additional packages from GitHub, such as tab layout and material icons. Will this increase the size of my project and its build? Are there any differences in file weight when incorporating these packages into my project compared to o ...

The command "npm install" does not automatically generate the node_modules directory, nor does it copy any .node files if the directory already exists

package.json { "name" : "xyzjs" "description" : "Sample project" "keywords": ["programming", "coding"], "version" : "1.0.0", "main": "./xyz.js" } this utilizes the binding.gyp in the current directory for project compilation, resulting in the ...