Skip to content

Unsupported require(esm) whe using vm.Script #61203

@SuperOleg39

Description

@SuperOleg39

Version

v24.12.0

Platform

Darwin macbook-JPF9H46PN7 24.6.0 Darwin Kernel Version 24.6.0: Mon Jul 14 11:30:29 PDT 2025; arm64

Subsystem

No response

What steps will reproduce the bug?

Hello!

We use a v8-compile-cache library and recently get error - Cannot use import statement outside a module for async-function package.

From async-function, exports.module-sync with ESM version is resolved:

"name": "async-function",
...,
"exports": {
	".": [
		{
			"module-sync": "./require.mjs",
			"import": "./index.mjs",
			"default": "./index.js"
		},
		"./index.js"
	],
	"./package.json": "./package.json"
}

v8-compile-cache uses vm.Script for compilation - https://github.com/zertosh/v8-compile-cache/blob/b6bc035d337fbda0e6e3ec7936499048fc9deafc/v8-compile-cache.js#L240

Simple reproduction without v8-compile-cache:

const vm = require('node:vm');

const success = require('async-function');

const failed = new vm.Script(
  `import getAsyncFunction from './index.js';

export default getAsyncFunction;

export { getAsyncFunction as 'module.exports' };`,
  {
    filename: './node_modules/async-function/require.mjs',
  }
);

There is no dynamic imports, or anyway importModuleDynamically should be used?

If this behaviour is expected, how can we compile both CJS and ESM modules in universal way?

How often does it reproduce? Is there a required condition?

Always

What is the expected behavior? Why is that the expected behavior?

I can use CJS and ESM in Script

What do you see instead?

SyntaxError: Cannot use import statement outside a module

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions