Skip to content

Unexpected error when using import ... from statement in eval #36985

Description

@TimDaub

I'm using Node LTS v14. I have a list of JavaScript files as strings that I'd like to evaluate. With CJS, this was possible using e.g. eval:

Welcome to Node.js v14.15.4.
Type ".help" for more information.
> eval("const fs = require('fs')");
undefined

With ESM, however:

Welcome to Node.js v14.15.4.
Type ".help" for more information.
> eval("import fs from 'fs'");
Uncaught SyntaxError: Cannot use import statement outside a module

Apart from using the dynamic import function, is there any possibility to use eval to evaluate ESM JavaScript? Is there any other reasonable way of evaluating? I found an approach that seems to work partially with Blobs and the dynamic import function (NOTE: It cannot resolve a dependency!). I've also looked at Workers, but it seems that issue is still open #30682. vm doesn't look like a fit either.

Any suggestions?

My expectation would either be that eval treats any input as a module, or that at least there's somehow a way to force eval to treat an input as a module, e.g. eval("string", { type: "module"});. Otherwise, how can any JavaScript be evaluate that contains the import ... from statement.

Activity

  1. aduh95 commented on Jan 18, 2021

    @aduh95
    Contributor

    You can either use vm.Module, or indeed using Workers and data: URLs:

    new Worker(new URL('data:text/javascript,import fs from "fs"'));

    I'm not sure to understand why is that useful to you. What are you trying to do with this? Are you trying to simply validate the syntax or do you expect to get a result from the code?

  2. jasnell commented on Jan 18, 2021

    @jasnell
    Member

    Given that eval() is defined by the language and provided by V8 (and not Node.js), there's really not going to be anything we can do here with how it works. You can try vm.Module or Worker as suggested but it's not entirely clear what the use case is so it's difficult to recommend an approach

  3. TimDaub commented on Jan 19, 2021

    @TimDaub
    Author

    @aduh95 thanks. The snippet you sent looks promising and I'll give it a go. The context is that I'd like to test the code in my README.md as can be seen here.

    there's really not going to be anything we can do here with how it works.

    OK, makes sense.

    Edit: @aduh95's example ended up working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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