Ways to resolve the error 'Cannot use import statement outside a module' while executing cdk deploy

https://i.sstatic.net/umv1S.png

In my project, I have a TypeScript and JavaScript blend structure. The bin folder contains a file that creates the CDK stack, while the lib folder holds all of my CDK code for creating AWS resources. However, within the lib folder, there are also multiple JS files that utilize React. My issue arises when attempting to execute 'cdk deploy' as it throws the error 'SyntaxError: Cannot use import statement outside a module'. Despite my efforts to add "type": "module" to my tsconfig file, I encountered another error stating `TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for .../bin/aws-cdk-namespace-deployment.ts`. This particular Typescript file resides in the bin folder and should indeed be using imports. Below is my tsconfig:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "baseUrl": ".",
    "target": "es2017",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react",
    "downlevelIteration": true
  },
  "include": [
    "src/**/*"
  ]
}

Here is my package.json:

... (package.json content follows)

Despite maintaining the application structure as detailed above, along with the provided tsconfig and package.json configurations, executing 'npm run build && cdk deploy' results in the same error: 'SyntaxError: Cannot use import statement outside a module'. Any assistance or suggestions on resolving this issue would be greatly appreciated.

Answer №1

To successfully manage TS files during the process, I follow this approach using tsx:

node ./node_modules/.bin/cdk --app='tsx ./src/cdk/myCDKStacks.ts'

If preferred, you can create a separate bin file - but personally, I directly reference my stack file as shown above. My stack file myCDKStack.ts contains the code for all stacks.

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

Getting the Correct Nested Type in TypeScript Conditional Types for Iterables

In my quest to create a type called GoodNestedIterableType, I aim to transform something from Iterable<Iterable<A>> to just A. To illustrate, let's consider the following code snippet: const arr = [ [1, 2, 3], [4, 5, 6], ] type GoodN ...

Select2 eliminates every tag except the first one

I am currently utilizing Select2 in Django for handling many-to-many relationships. The best approach I have found to handle all validation constraints is to create related objects through an AJAX request as soon as they are entered into the Select2 tag fi ...

What is the method for retrieving a child element using its ID in JavaScript?

Below is the HTML code I am working with: <div id="note"> <textarea id="textid" class="textclass">Text</textarea> </div> I am trying to retrieve the textarea element without using document.getElementById("textid"). This is what I ...

Is there a way to extract a single row from a database with each button click?

I am working on a system for selecting items and need assistance with iterating through a table one item at a time upon clicking a button. Currently, the button only displays the first item in the table. How can I modify it to cycle through each item one b ...

Unable to automatically close browser window after test execution with NightwatchJS

I recently executed my first Nightwatch test, as indicated in the code below. The test ran smoothly - Selenium successfully entered 'wiki' into Google and submitted the form, resulting in a passing test. However, I am now looking to automate the ...

Enabling CORs headers in Express continues to lead to errors

I have implemented the CORS code provided on http://enable-cors.org/ for express into my index.js file. /*these first five line direct from http://enable-cors.org/.com*/ app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); ...

Incorporating a Layered Div onto a Presentation Slider

Over at , we have a slider featured on the homepage. I am attempting to place a div ABOVE the image but BELOW the text. Essentially, my goal is to add a semi-transparent white overlay to enhance the image on the slider while keeping the text visible for b ...

Receiving response from Jquery-loaded content using postback

Let's start with some context: The main Aspx page I have (which uses a Master Page) contains multiple Web User Controls, most of which are wrapped in their own Update Panels. One particular control can take a few seconds to load, significantly impac ...

Issue with Line 126: Syntax Error Unexpected End - Troubleshooting Required

Encountering an issue in my JS/HTML5 pong game project at line 126: tennisJS_game.html:126 Uncaught SyntaxError: Unexpected end of input I can't seem to pinpoint the error. I have closed the function and everything else appears correct. Below is th ...

Utilize Python's multiprocessing capabilities along with a communication interface to enhance efficiency

Currently, I am in the process of converting JavaScript code to Python. One challenge I am facing is that JavaScript runs code asynchronously and offers a simple event emitter-listener function for inter-instance communication. Is there a comparable method ...

When I try to add more content to my page, it doesn't extend beyond a single page and instead gets compacted together

As a beginner in the world of coding, my goal is to create a time management website specifically tailored for school use. Despite copying this code multiple times, I have encountered an issue where it does not continue down the page, and I am unsure of th ...

Insert newly added rows' values into the database dynamically

Hello there, I'm currently working on a PHP form that needs to dynamically add a table row when the "Add" button is pressed. I'm using a for loop to save the values, but I'm running into an issue where the data is not being saved into my dat ...

Troubleshooting in React: Addressing the issue of missing property 'children' in type '{ }' while it is required in type 'Props'

I am working with two components, card and cardList. My goal is to include the cardList component in the App component to display a list of fetched data in cards. However, I am struggling with connecting these two components in order to correctly display ...

JavaScript: An object containing a unified handler for all method invocations

Let me explain further. Math.add(2, 2) //4 Math.multiply(4, 9) //36 Whenever a method in the Math object is invoked, it triggers a central processor that interprets the function name to determine its action. Can an object execute a default function when ...

Using bootstrap with a navbar in an asp.net mvc application proves to be challenging

There are only a few bootstraps that work with this site, such as the default and lumen bootstrap. You can find them on However, other bootstraps like materia and flatly seem to be causing display issues. Here's an example of how it looks: Edit: Bel ...

The "results per page" ajax dropdown in Yii stops working after other ajax content is loaded on the page

One of the views in Yii framework is the "Patients" view, which contains several CGridViews and other elements that are loaded via ajax after the initial view has loaded. Some of these elements are nested within multiple levels of ajax-loaded divs. Within ...

What could be the reason for receiving an array of promises instead of data while fetching information from the blockchain using useEffect?

I've encountered an issue while working with React and fetching data from the blockchain using useEffect. The problem arises when I map the data and store it in the lendingData array - upon logging, it appears as though I'm getting an array of pr ...

Supabase Type Generation Not Working as Expected

Every time I try to update my typing through the cli command, I keep getting this error message without much information for me to troubleshoot. 2023/03/01 09:34:01 Recv First Byte Error: failed to retrieve generated types: {"message":"Forbi ...

Trouble getting JavaScript variables to properly insert into strings when sending them to an HTML document

Struggling with variable interpolation in JavaScript strings. I need to replace the words_to_be_removed variable with the defaultMessageTest string, but none of my attempted methods are working. Here are the three methods I tried: String text ${expressi ...

Angular filter is causing an error message saying "Unable to interpolate," but the filter is functioning as expected

I have implemented the filter below (which I found on StackOverflow) that works perfectly fine on one page. However, when using the same object, it throws an error as shown below: app.filter('dateFormat', function dateFormat($filter){ return f ...