Skip to content

Next 12 - ESM Support - SyntaxError: Cannot use import statement outside a module #30441

@DaniAkash

Description

@DaniAkash

What version of Next.js are you using?

12.0.1

What version of Node.js are you using?

14.18.1

What browser are you using?

Chrome

What operating system are you using?

Linux

How are you deploying your application?

Vercel / CodeSandbox

Describe the Bug

Trying to import a ES Module in Next.js 12 throws the following error:

Example based on Tree shakable ESM export of validator library but happens with any other esm package

Server Error
SyntaxError: Cannot use import statement outside a module

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
<unknown>
file:///sandbox/node_modules/validator/es/lib/isEmail.js (1)
wrapSafe
internal/modules/cjs/loader.js (1001:16)
Module._compile
internal/modules/cjs/loader.js (1049:27)
Object.Module._extensions..js
internal/modules/cjs/loader.js (1114:10)
Module.load
internal/modules/cjs/loader.js (950:32)
Function.Module._load
internal/modules/cjs/loader.js (790:12)
Module.require
internal/modules/cjs/loader.js (974:19)
require
internal/modules/cjs/helpers.js (93:18)
Object.validator/es/lib/isEmail
file:///sandbox/.next/server/pages/index.js (318:18)
__webpack_require__
file:///sandbox/.next/server/webpack-runtime.js (33:42)
eval
webpack-internal:///./pages/index.js (9:82)

Expected Behavior

ES Modules should work in Next.js 12

To Reproduce

Visit the following codesandbox:

https://codesandbox.io/s/next-12-esm-issue-nlew9?file=/pages/index.js:62-110

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIssue was opened via the bug report template.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions