Skip to content

ESM builds in packages are interpreted as CommonJS #73363

@anomiex

Description

@anomiex

Whether a file with a .js extension is supposed to contain ESM or CommonJS code is determined by whether the nearest package.json sets the type field to module. Most of the packages in Gutenberg do not have the type field, meaning that the .js files in build-module are incorrectly interpreted as CommonJS by various tooling.

This happens to work ok with bundlers such as Webpack and transpilers such as Babel, since they are very lenient in what they accept. On the other hand, Jest running in native-ESM mode (rather than transpiling everything through Babel) chokes on this.

  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    [...]

    Details:

    /tmp/test/node_modules/@wordpress/dataviews/build-module/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as DataViews } from './components/dataviews';
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)

There are several ways to fix this:

  • Name the files in build-module (and any other ESM-containing files) with the .mjs extension instead of .js.
  • Set type to module in package.json, and name any files containing CommonJS code with the .cjs extension instead of .js.
  • Since it’s the nearest package.json rather than the package’s package.json that counts, you could add additional package.json files in subdirs to change the type setting. Note these would also need to copy sideEffects and other fields, so this probably isn’t a very good solution.

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