nrwl / nx

Smart Monorepos · Fast CI
https://nx.dev
MIT License
23.42k stars 2.34k forks source link

SyntaxError: Cannot use import statement outside a module #22948

Closed beeman closed 4 months ago

beeman commented 5 months ago

Current Behavior

Tests don't run when extending the @nx/react-native application generator. Getting the message Jest encountered an unexpected token and SyntaxError: Cannot use import statement outside a module.

Expected Behavior

Tests run without Jest encountered an unexpected token message

GitHub Repo

https://github.com/beeman/custom-react-native/

Steps to Reproduce

  1. pnpx create-nx-workspace@latest custom-react-native
  2. cd custom-react-native
  3. pnpm install -D @nx/plugin @nx/react-native
  4. pnpm nx g @nx/plugin:plugin preset-react-native --directory packages/preset-react-native --bundler rollup --unitTestRunner jest --publishable --import-path @custom-react-native/preset-react-native --project-name-and-root-format as-provided
  5. pnpm nx g @nx/plugin:generator react-native-application --directory packages/preset-react-native/src/generators/react-native-application --nameAndDirectoryFormat as-provided
  6. Update the generator as per this commit
  7. Run the tests: pnpm nx test preset-react-native
  8. See the error.

Nx Report

NX   Report complete - copy this into the issue template

Node   : 20.9.0
OS     : darwin-arm64
pnpm   : 8.15.5

nx                 : 18.3.3
@nx/js             : 18.3.3
@nx/jest           : 18.3.3
@nx/linter         : 18.3.3
@nx/eslint         : 18.3.3
@nx/workspace      : 18.3.3
@nx/devkit         : 18.3.3
@nx/eslint-plugin  : 18.3.3
@nx/plugin         : 18.3.3
@nx/react          : 18.3.3
@nx/react-native   : 18.3.3
@nrwl/tao          : 18.3.3
@nx/web            : 18.3.3
@nx/webpack        : 18.3.3
typescript         : 5.4.5
---------------------------------------
Local workspace plugins:
         @custom-react-native/preset-react-native

Failure Logs

pnpm nx run-many -t test -u

 NX   Running target test for project preset-react-native

   ✖  nx run preset-react-native:test
       FAIL   preset-react-native  packages/preset-react-native/src/generators/react-native-application/generator.spec.ts
        ● 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.

          Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

          By default "node_modules" folder is ignored by transformers.

          Here's what you can do:
           • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
           • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
           • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
           • If you need a custom transformation specify a "transform" option in your config.
           • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

          You'll find more details and examples of these config options in the docs:
          https://jestjs.io/docs/configuration
          For information about custom transformations, see:
          https://jestjs.io/docs/code-transformation

          Details:

          /Users/beeman/dev/github/solana-developers/custom-react-native/node_modules/.pnpm/@nx+react-native@18.3.3_@swc-node+register@1.8.0_@swc+core@1.3.107_@types+node@18.16.9_nx@18._c2cixo6fpj6y5a2vbzvluh65lq/node_modules/@nx/react-native/src/executors/sync-deps/sync-deps.impl.ts:1
          ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { join } from 'path';
                                                                                            ^^^^^^

          SyntaxError: Cannot use import statement outside a module

            1 | import { getProjects, Tree } from '@nx/devkit';
            2 | import { Linter } from '@nx/eslint';
          > 3 | import { reactNativeApplicationGenerator } from '@nx/react-native';
              | ^
            4 | import { NormalizedReactNativeApplicationSchema } from './normalize-react-native-application-schema';
            5 |
            6 | export async function generateReactNativeApplication(

            at Runtime.createScriptFromCode (../../node_modules/.pnpm/jest-runtime@29.7.0/node_modules/jest-runtime/build/index.js:1505:14)
            at Object.<anonymous> (../../node_modules/.pnpm/@nx+react-native@18.3.3_@swc-node+register@1.8.0_@swc+core@1.3.107_@types+node@18.16.9_nx@18._c2cixo6fpj6y5a2vbzvluh65lq/node_modules/@nx/react-native/src/generators/application/application.js:18:26)
            at Object.<anonymous> (../../node_modules/.pnpm/@nx+react-native@18.3.3_@swc-node+register@1.8.0_@swc+core@1.3.107_@types+node@18.16.9_nx@18._c2cixo6fpj6y5a2vbzvluh65lq/node_modules/@nx/react-native/index.js:6:21)
            at Object.<anonymous> (src/utils/generate-react-native-application.ts:3:1)
            at Object.<anonymous> (src/utils/index.ts:1:1)
            at Object.<anonymous> (src/generators/react-native-application/generator.ts:2:1)
            at Object.<anonymous> (src/generators/react-native-application/generator.spec.ts:4:1)

      Test Suites: 1 failed, 1 total
      Tests:       0 total
      Snapshots:   0 total
      Time:        0.866 s
      Ran all test suites.

—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

 NX   Ran target test for project preset-react-native (2s)

      With additional flags:
        --u=true

   ✔  0/1 succeeded [0 read from cache]

   ✖  1/1 targets failed, including the following:

      - nx run preset-react-native:test

Package Manager Version

No response

Operating System

Additional Information

I'm using the same setup with the @nx/react and @nx/next package and that works as expected.

lucavb commented 5 months ago

I am facing similar issues with version 18.3.x where Jest is telling me this

        ● finish project generator › runs successfully

          TypeError: A dynamic import callback was invoked without --experimental-vm-modules

            10 |         const projectName = 'my-cool-project-name';
            11 |         const tree = createTreeWithEmptyWorkspace();
          > 12 |         await libraryGenerator(tree, {
               |         ^
            13 |             compiler: 'tsc',
            14 |             importPath: `@foobar/${projectName}`,
            15 |             name: projectName,

            at Object.<anonymous> (../../node_modules/prettier/index.cjs:593:23)
            at ensurePackage (../../node_modules/@nx/devkit/src/utils/package-json.js:279:16)
            at initGenerator (../../node_modules/@nx/js/src/generators/init/init.js:103:32)
            at libraryGeneratorInternal (../../node_modules/@nx/js/src/generators/library/library.js:30:16)
            at libraryGenerator (../../node_modules/@nx/js/src/generators/library/library.js:19:12)
            at libraryGeneratorInternal (../../node_modules/@nx/node/src/generators/library/library.js:32:28)
            at libraryGenerator (../../node_modules/@nx/node/src/generators/library/library.js:14:12)
            at Object.<anonymous> (src/generators/finish-project/generator.spec.ts:12:9)

The line in question in Prettier:

Screenshot 2024-04-23 at 08 39 54

(Simply adding this NODE_OPTIONS argument does not work for us at least because it breaks another package in our monorepo)

haladamateusz commented 5 months ago

I'm facing the same error in Angular monorepo. Everything was working correctly in nx@18.0.8. After running migrations I can't get tests to pass.

   ×  nx run angular:test
      TypeError: A dynamic import callback was invoked without --experimental-vm-modules
    at importModuleDynamicallyCallback (node:internal/modules/esm/utils:211:11)
    at Object.<anonymous> (C:\Users\mathal\Projects\mygudel\Frontend\node_modules\prettier\index.cjs:593:23)
    at Runtime._execModule (C:\Users\mathal\Projects\mygudel\Frontend\node_modules\jest-runtime\build\index.js:1439:24)
    at Runtime._loadModule (C:\Users\mathal\Projects\mygudel\Frontend\node_modules\jest-runtime\build\index.js:1022:12)
    at Runtime.requireModule (C:\Users\mathal\Projects\mygudel\Frontend\node_modules\jest-runtime\build\index.js:882:12)
    at Runtime.requireModuleOrMock (C:\Users\mathal\Projects\mygudel\Frontend\node_modules\jest-runtime\build\index.js:1048:21)
    at ensurePackage (C:\Users\mathal\Projects\mygudel\Frontend\node_modules\@nx\devkit\src\utils\package-json.js:279:16)
    at initGenerator (C:\Users\mathal\Projects\mygudel\Frontend\node_modules\@nx\js\src\generators\init\init.js:103:32)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async applicationGeneratorInternal (C:\Users\mathal\Projects\mygudel\Frontend\node_modules\@nx\angular\src\generators\application\application.js:22:5)
    at async applicationGenerator (C:\Users\mathal\Projects\mygudel\Frontend\node_modules\@nx\angular\src\generators\application\application.js:13:12) {
  code: 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG'
}

EDIT: Setting NODE_OPTIONS=--experimental-vm-modules in root .env file causes other tests to fail.

eriktoyra commented 4 months ago

Facing the same problem in a React + Node monorepo since after upgrading from NX 18.0.4 to 18.3.3.

> nx run [redacted]-nx-generators:test --runInBand

  console.warn
    In Nx 19, generating projects will no longer derive the name and root.
    Please provide the exact project name and root in the future.
    Example: nx g @nx/js:library test --directory test

      at Object.warn (../../node_modules/nx/src/utils/logger.js:8:26)
      at logDeprecationMessage (../../node_modules/@nx/devkit/src/generators/project-name-and-root-utils.js:48:12)
      at determineProjectNameAndRootOptions (../../node_modules/@nx/devkit/src/generators/project-name-and-root-utils.js:19:9)
      at normalizeOptions (../../node_modules/@nx/js/src/generators/library/library.js:500:151)
      at libraryGeneratorInternal (../../node_modules/@nx/js/src/generators/library/library.js:35:27)
      at async libraryGenerator (../../node_modules/@nx/js/src/generators/library/library.js:19:12)

TypeError: A dynamic import callback was invoked without --experimental-vm-modules
    at importModuleDynamicallyCallback (node:internal/modules/esm/utils:180:11)
    at Object.<anonymous> (/__w/1/s/node_modules/prettier/index.cjs:593:23)
    at Runtime._execModule (/__w/1/s/node_modules/jest-runtime/build/index.js:1439:24)
    at Runtime._loadModule (/__w/1/s/node_modules/jest-runtime/build/index.js:1022:12)
    at Runtime.requireModule (/__w/1/s/node_modules/jest-runtime/build/index.js:882:12)
    at Runtime.requireModuleOrMock (/__w/1/s/node_modules/jest-runtime/build/index.js:1048:21)
    at ensurePackage (/__w/1/s/node_modules/@nx/devkit/src/utils/package-json.js:279:16)
    at initGenerator (/__w/1/s/node_modules/@nx/js/src/generators/init/init.js:103:32)
    at async libraryGeneratorInternal (/__w/1/s/node_modules/@nx/js/src/generators/library/library.js:30:16)
    at async libraryGenerator (/__w/1/s/node_modules/@nx/js/src/generators/library/library.js:19:12) {
  code: 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG'
}
gal1419 commented 4 months ago

Facing the same issue,

` ❌ > nx run workspace:test --passWithNoTests

jest --passWithNoTests TypeError: A dynamic import callback was invoked without --experimental-vm-modules at importModuleDynamicallyCallback (node:internal/modules/esm/utils:226:11) at Object. (/home/runner/work/nuko/nuko/node_modules/.pnpm/prettier@3.2.5/node_modules/prettier/index.cjs:593:23) at Runtime._execModule (/home/runner/work/nuko/nuko/node_modules/.pnpm/jest-runtime@29.7.0/node_modules/jest-runtime/build/index.js:1439:24) at Runtime._loadModule (/home/runner/work/nuko/nuko/node_modules/.pnpm/jest-runtime@29.7.0/node_modules/jest-runtime/build/index.js:1022:12) at Runtime.requireModule (/home/runner/work/nuko/nuko/node_modules/.pnpm/jest-runtime@29.7.0/node_modules/jest-runtime/build/index.js:882:12) at Runtime.requireModuleOrMock (/home/runner/work/nuko/nuko/node_modules/.pnpm/jest-runtime@29.7.0/node_modules/jest-runtime/build/index.js:1048:21) at ensurePackage (/home/runner/work/nuko/nuko/node_modules/.pnpm/@nx+devkit@19.0.4_nx@19.0.4/node_modules/@nx/devkit/src/utils/package-json.js:279:16) at initGenerator (/home/runner/work/nuko/nuko/nodemodules/.pnpm/@nx+js@19.0.4@swc-node+register@1.8.0@swc+core@1.4.2@types+node@20.11.19_nx@19.0.4_typescript@5.4.3/node_modules/@nx/js/src/generators/init/init.js:105:32) at async libraryGeneratorInternal (/home/runner/work/nuko/nuko/nodemodules/.pnpm/@nx+js@19.0.4@swc-node+register@1.8.0@swc+core@1.4.2@types+node@20.11.19_nx@19.0.4_typescript@5.4.3/node_modules/@nx/js/src/generators/library/library.js:30:16) at async libraryGenerator (/home/runner/work/nuko/nuko/nodemodules/.pnpm/@nx+js@19.0.4@swc-node+register@1.8.0@swc+core@1.4.2@types+node@20.11.19_nx@19.0.4_typescript@5.4.3/node_modules/@nx/js/src/generators/library/library.js:19:12) at async libraryGeneratorInternal (/home/runner/work/nuko/nuko/nodemodules/.pnpm/@nx+nest@19.0.4@swc-node+register@1.8.0@swc+core@1.4.2@types+node@20.11.19_nx@19.0.4_ts-node@10.9.2_typescript@5.4.3/node_modules/@nx/nest/src/generators/library/library.js:20:5) at async libraryGenerator (/home/runner/work/nuko/nuko/nodemodules/.pnpm/@nx+nest@19.0.4@swc-node+register@1.8.0@swc+core@1.4.2@types+node@20.11.19_nx@19.0.4_ts-node@10.9.2_typescript@5.4.3/node_modules/@nx/nest/src/generators/library/library.js:11:12) { code: 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG' }

`

schoggobaer commented 4 months ago

facing the same issue with other generators (angular/node) after upgrading from NX 18.0.8 to 18.3.4.

Markus-Ende commented 4 months ago

Had the same issue when upgrading to nx 19.1.0, fixed by deleting .angular cache 🤦

haladamateusz commented 4 months ago

Had the same issue when upgrading to nx 19.1.0, fixed by deleting .angular cache 🤦

Doesn't work in my case, even after removing .angular cache. It still fails in both places - in local environment and during pipeline run.

beeman commented 4 months ago

Had the same issue when upgrading to nx 19.1.0, fixed by deleting .angular cache 🤦

Doesn't work in my case, even after removing .angular cache. It still fails in both places - in local environment and during pipeline run.

Same, in my case it happens in a project that doesn't use Angular. Just plain Nx with the default generators 🤷‍♂️

pete-mcwilliams commented 4 months ago

This is affecting angular environments also ("@nx/angular": "19.1.0")

I'm also getting this error after update to nx 19.1.0 from 18.0.4.

In common with some of the other comments I also see this reported in generator.spec.ts

> nx run plugins:test

Option "tsConfig" is deprecated: Use the ts-jest configuration options in the jest config file instead.
  console.warn
    In Nx 20, generating projects will no longer derive the name and root.
    Please provide the exact project name and root in the future.
    Example: nx g @nx/angular:library test --directory test

      27 |
      28 |   // run nx angular library generator
    > 29 |   await libraryGenerator(tree, { name: options.name, skipModule: true, strict: true, directory: options.directory });
         |                         ^
      30 |
      31 |   // update config to match our requirements
      32 |   await updateJestConfig(tree, normalisedOptions);

      at Object.warn (../../node_modules/nx/src/utils/logger.js:8:26)
      at logDeprecationMessage (../../node_modules/@nx/devkit/src/generators/project-name-and-root-utils.js:47:29)
      at determineProjectNameAndRootOptions (../../node_modules/@nx/devkit/src/generators/project-name-and-root-utils.js:18:9)
      at normalizeOptions (../../node_modules/@nx/angular/src/generators/library/lib/normalize-options.js:25:151)
      at libraryGeneratorInternal (../../node_modules/@nx/angular/src/generators/library/library.js:45:68)
      at libraryGenerator (../../node_modules/@nx/angular/src/generators/library/library.js:26:18)
      at src/generators/lib/generator.ts:29:25
      at ../../node_modules/tslib/tslib.js:169:75
      at Object.__awaiter (../../node_modules/tslib/tslib.js:165:16)
      at default_1 (src/generators/lib/generator.ts:21:20)
      at src/generators/lib/generator.spec.ts:16:20
      at ../../node_modules/tslib/tslib.js:169:75
      at Object.__awaiter (../../node_modules/tslib/tslib.js:165:16)
      at Object.<anonymous> (src/generators/lib/generator.spec.ts:15:44)

  console.warn
    Couldn't find .gitignore file to update

      at Object.warn (../../node_modules/nx/src/utils/logger.js:8:26)
      at addGitIgnoreEntry (../../node_modules/@nx/angular/src/generators/init/init.js:51:25)
      at ignoreAngularCacheDirectory (../../node_modules/@nx/angular/src/generators/init/init.js:38:5)
      at angularInitGenerator (../../node_modules/@nx/angular/src/generators/init/init.js:7:5)
      at libraryGeneratorInternal (../../node_modules/@nx/angular/src/generators/library/library.js:53:30)
      at async libraryGenerator (../../node_modules/@nx/angular/src/generators/library/library.js:26:12)

TypeError: A dynamic import callback was invoked without --experimental-vm-modules
    at importModuleDynamicallyCallback (node:internal/modules/esm/utils:226:11)
    at Object.<anonymous> (<snip>/node_modules/prettier/index.cjs:593:23)
    at Runtime._execModule (<snip>/node_modules/jest-runtime/build/index.js:1439:24)
    at Runtime._loadModule (<snip>/node_modules/jest-runtime/build/index.js:1022:12)
    at Runtime.requireModule (<snip>/node_modules/jest-runtime/build/index.js:882:12)
    at Runtime.requireModuleOrMock (<snip>/node_modules/jest-runtime/build/index.js:1048:21)
    at ensurePackage (<snip>/node_modules/@nx/devkit/src/utils/package-json.js:279:16)
    at initGenerator (<snip>/node_modules/@nx/js/src/generators/init/init.js:105:32)
    at async libraryGeneratorInternal (<snip>/node_modules/@nx/angular/src/generators/library/library.js:48:5)
    at async libraryGenerator (<snip>/node_modules/@nx/angular/src/generators/library/library.js:26:12) {
  code: 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG'
}

 RUNS   plugins  libs/plugins/src/generators/lib/generator.spec.ts
0xCourtney commented 4 months ago

bump

lucavb commented 4 months ago

For the record, the issue also still persists in the most recent version of Nx.

wkoutre commented 4 months ago

I was facing this issue when trying to import like this in one of my unit tests:

import { reactNativeLibraryGenerator } from '@nx/react-native';

In node_modules/@nx/react-native/src/generators/application/application.js, there's

const sync_deps_impl_1 = require("../../executors/sync-deps/sync-deps.impl");

The problem is that there is a sync-deps.impl.ts file in that directory, which is the problem. If it's changed to be...

const sync_deps_impl_1 = require("../../executors/sync-deps/sync-deps.impl.js");

...then my tests pass.

Alternatively, I'm able to change my import to the following, which also works.

import { reactNativeLibraryGenerator } from '@nx/react-native/src/generators/library/library.js';
xiongemi commented 4 months ago

i think this issue happens because the final react native package includes .ts files where it should not, i submit a pr https://github.com/nrwl/nx/pull/26352 to fix that. the error with angular is a separate issue.

xiongemi commented 4 months ago

I am facing similar issues with version 18.3.x where Jest is telling me this

        ● finish project generator › runs successfully

          TypeError: A dynamic import callback was invoked without --experimental-vm-modules

            10 |         const projectName = 'my-cool-project-name';
            11 |         const tree = createTreeWithEmptyWorkspace();
          > 12 |         await libraryGenerator(tree, {
               |         ^
            13 |             compiler: 'tsc',
            14 |             importPath: `@foobar/${projectName}`,
            15 |             name: projectName,

            at Object.<anonymous> (../../node_modules/prettier/index.cjs:593:23)
            at ensurePackage (../../node_modules/@nx/devkit/src/utils/package-json.js:279:16)
            at initGenerator (../../node_modules/@nx/js/src/generators/init/init.js:103:32)
            at libraryGeneratorInternal (../../node_modules/@nx/js/src/generators/library/library.js:30:16)
            at libraryGenerator (../../node_modules/@nx/js/src/generators/library/library.js:19:12)
            at libraryGeneratorInternal (../../node_modules/@nx/node/src/generators/library/library.js:32:28)
            at libraryGenerator (../../node_modules/@nx/node/src/generators/library/library.js:14:12)
            at Object.<anonymous> (src/generators/finish-project/generator.spec.ts:12:9)

The line in question in Prettier:

Screenshot 2024-04-23 at 08 39 54

(Simply adding this NODE_OPTIONS argument does not work for us at least because it breaks another package in our monorepo)

this is a separate issue from the one in the description. is it possible to submit a github issue and also link a repo to reproduce this issue?

github-actions[bot] commented 3 months ago

This issue has been closed for more than 30 days. If this issue is still occuring, please open a new issue with more recent context.