Cannot use import statement outside a module in serverless node application
The error message “Cannot use import statement outside a module” occurs when you try to use an import
statement in a Node.js application that is not configured to handle ECMAScript modules (ES modules) syntax.
To resolve this issue in a serverless Node.js application, you can follow these steps:
- Ensure Node.js version supports ECMAScript modules: Verify that you are using a Node.js version that supports ECMAScript modules. Starting from Node.js version 12, ECMAScript modules are supported by default. If you are using an older version, consider upgrading to a supported version.
- Use CommonJS syntax for imports: If you are unable to use ECMAScript modules in your current setup, you can switch to using CommonJS syntax for imports. Replace your
import
statements withrequire
statements. For example:
// Before import express from 'express'; // After const express = require('express');
Update all your import statements to use require
syntax.
- Configure ECMAScript modules (optional): If you have a specific requirement to use ECMAScript modules in your serverless application, you may need to update your project’s configuration to support it. For example, if you are using the Serverless Framework, you can configure the
serverless.yml
file to useesm
(ECMAScript module loader) or enable transpilation using Babel. Here’s an example configuration usingesm
:
# serverless.yml service: my-service provider: name: aws runtime: nodejs14.x functions: myFunction: handler: src/index.handler environment: NODE_OPTIONS: "--loader ts-node/esm" plugins: - serverless-offline
This configuration allows you to use ECMAScript modules with the esm
loader.
By either using CommonJS syntax or configuring ECMAScript modules, you can resolve the “Cannot use import statement outside a module” error in your serverless Node.js application.
Leave a Comment