Haul: jest (babel) fails if using ES6 imports

Created on 10 Oct 2019  路  5Comments  路  Source: callstack/haul

Environment

devDependencies:

"@haul-bundler/babel-preset-react-native": "^0.13.2",
"@haul-bundler/cli": "^0.13.1",
"@haul-bundler/preset-0.60": "^0.13.0",
"jest": "^24.9.0",

Node v12.4.0

Description

After changing babel.config.js preset @haul-bundler/babel-preset-react-native jest tests don't support import syntax anymore. If switching back to metro-react-native-babel-preset jest works again.

Trying to figure out what setting is triggering this, but not expert in babel configuration.

Getting errors such as

    import fetch, { Headers } from 'node-fetch';
           ^^^^^

    SyntaxError: Unexpected identifier

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
bug

Most helpful comment

@jounii Looks a bit hacky, you can alternatively try this:

env: {
  test: {
    plugins: [['@babel/plugin-transform-modules-commonjs', { allowTopLevelThis: true }]]
  }
}

It should work for every file if it's being run by Jest, which sets process.env.NODE_ENV to test.

All 5 comments

@jounii
Add this workaround to your Babel config:

overrides: [
  {
    test: /__tests__/,
    plugins: [['@babel/plugin-transform-modules-commonjs', { allowTopLevelThis: true }]]
  }
]

Thanks. Your example pointed to right direction, however it was not enough because the jest is running and parsing all sort of files. Only common here was that it is running inside node.

So not sure if it is correct way, but this seems to work for now at least:

const isNode = () => typeof process === 'object'
    overrides: [
        {
            test: isNode,
            plugins: [
                ['@babel/plugin-transform-modules-commonjs', { allowTopLevelThis: true }]
            ]
        }
    ]

@jounii Looks a bit hacky, you can alternatively try this:

env: {
  test: {
    plugins: [['@babel/plugin-transform-modules-commonjs', { allowTopLevelThis: true }]]
  }
}

It should work for every file if it's being run by Jest, which sets process.env.NODE_ENV to test.

Thanks, that looks better solution and works too. Not familiar with babel config that well, but makes sense now how it works.

In next release of @haul-bundler/babel-preset-react-native CommonJS transform will be added automatically in when NODE_ENV === 'test', like above.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xareelee picture xareelee  路  5Comments

MichelDiz picture MichelDiz  路  3Comments

hesyifei picture hesyifei  路  4Comments

Traviskn picture Traviskn  路  4Comments

jurajkrivda picture jurajkrivda  路  4Comments