question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

fix: Cannot use import statement outside a module

See original GitHub issue

🐛 The bug Since I upgraded to 0.33.0, my tests are not passing anymore because it seems like Jest is pointing to the wrong file. node_modules/@nuxtjs/composition-api/dist/runtime/index.mjs instead of node_modules/@nuxtjs/composition-api/dist/runtime/index.js

Full output

 FAIL   bddf-bodyguard  my-project/test/integration/components/MyComponentTest.test.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:

    /my-project/node_modules/.pnpm/@nuxtjs+composition-api@0.33.0_ndg5g6d2rkyeqt4q3tlrv66tjm/node_modules/@nuxtjs/composition-api/dist/runtime/index.mjs:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { getCurrentInstance as getCurrentInstance$1, ref, customRef, shallowRef, onServerPrefetch, isRef, reactive, toRefs, watch, computed, isReactive, toRaw, onBeforeMount, set } from 'vue';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    [...]

      at Runtime.createScriptFromCode (../../node_modules/.pnpm/jest-runtime@28.1.3/node_modules/jest-runtime/build/index.js:1796:14)
      at Object.<anonymous> (components/MyComponent.vue:9:27)
      at Object.<anonymous> (test/integration/components/MyComponentTest.test.ts:6:1)

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

🛠️ To reproduce Steps to reproduce the behavior:

  1. Create a new Nuxt 2 project
  2. Configure Jest
  3. Install @nuxtjs/composition-api@0.33.0
  4. Try to launch your tests

Repro here: https://stackblitz.com/edit/nuxt-starter-btq2rq?file=jest.config.ts

🌈 Expected behaviour Tests pass

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
theolavauxcommented, Aug 8, 2022

Whoops yeah, I’m working on an Nx repo and I forgot that my node_modules is not directly located in the project itself, it works now, thanks, you rock 🎸

0reactions
dvouletycommented, Sep 21, 2022

Hi @danielroe, after updating to 0.33.1, I got also error SyntaxError: Cannot use import statement outside a module. So I added node_modules/@nuxtjs/composition-api/dist/runtime/index.js to jest.config.js. But now I get this error:

const vue_1 = require("vue");
          ^

    SyntaxError: Identifier 'vue_1' has already been declared

      17 | import { defineAsyncComponent, computed, watch, onMounted } from 'vue'
      18 | import { useContext, useRoute, useAsync } from '@nuxtjs/composition-api'
    > 19 | import SearchResults from '@/components/SearchResults.vue'
         | ^

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1678:14)
      at Object.<anonymous> (src/components/SearchRequest.vue:19:1)
      at Object.<anonymous> (tests/setupEnv.js:8:1)

Any idea?

My jest.config.js

module.exports = {
  testEnvironment: 'jsdom',
  testEnvironmentOptions: {
    url: 'http://localhost/',
  },
  moduleFileExtensions: [
    'ts',
    'js',
    'vue',
  ],
  moduleNameMapper: {
    '^@/(.*\\.svg)': '<rootDir>/src/$1',
    '^@/(.*)$': '<rootDir>/src/$1',
    '^@@/(.*)$': '<rootDir>/$1',
    '(@visable-dev.*\\.svg)\\?': '$1',
    '^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^pinia$': 'pinia/dist/pinia.cjs',
    '^@nuxtjs/composition-api$': '<rootDir>/node_modules/@nuxtjs/composition-api/dist/runtime/index.js',
  },
  transform: {
    '^.+\\.(ts)$': 'ts-jest',
    '^.+\\.svg': '<rootDir>/tests/support/svgTransform.js',
    '^.+\\.vue$': '@vue/vue2-jest',
    '^.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.json': '<rootDir>/tests/support/jsonTransform.js',
    '.+': 'babel-jest',
  },
  testMatch: [
    '**/tests/**/*.spec.(js|ts)',
  ],
  setupFiles: [
    './tests/setup.js',
  ],
  setupFilesAfterEnv: [
    './tests/setupEnv.js',
  ],
}

my package.json

{
  "name": "unified-search-frontend",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "generate": "nuxt generate",
    "start": "nuxt start",
    "test": "jest -c jest.config.js",
    "cypress": "cypress run",
    "lint": "yarn lint:js && yarn lint:css",
    "typecheck": "vue-tsc --noEmit --skipLibCheck --project tsconfig.json && vue-tsc --noEmit --skipLibCheck --project cypress/tsconfig.json",
    "lint:js": "eslint --fix --ext ts,js,vue src tests *.js *.ts",
    "lint:css": "stylelint --fix \"**/*.css\" \"**/*.scss\" \"**/*.vue\" \"!**/dist/**\""
  },
  "dependencies": {
    "@intlify/vue-i18n-loader": "^1.0.0",
    "@koumoul/nuxt-config-inject": ">=0.4.12",
    "@maxmind/geoip2-node": ">=3.4.0",
    "@nuxtjs/composition-api": "^0.33.1",
    "@pinia/nuxt": "0.2.1",
    "@popperjs/core": "^2.11.6",
    "@sentry/browser": ">=7.8.0",
    "@sentry/integrations": ">=7.8.0",
    "@sentry/node": ">=7.8.0",
    "axios": ">=0.27.2",
    "body-scroll-lock": ">=3.1.5",
    "cookie-universal-nuxt": "^2.2.1",
    "dd-trace": ">=2.12.1",
    "fuse.js": ">=6.6.2",
    "http-proxy-middleware": ">=2.0.6",
    "ipaddr.js": ">=2.0.0",
    "maplibre-gl": "^2.1.9",
    "morgan": ">=1.10.0",
    "nuxt": "^2.15.8",
    "pinia": "^2.0.22",
    "portal-vue": ">=2.1.7",
    "routing-pattern": ">=1.0.4",
    "throttle-debounce": ">=5.0.0",
    "tracking": ">=1.1.3",
    "vue-i18n": "^8.27.2",
    "vue-lazy-hydration": ">=2.0.0-beta.4"
  },
  "devDependencies": {
    "@babel/core": ">=7.18.9",
    "@babel/eslint-parser": ">=7.18.9",
    "@babel/preset-env": ">=7.18.9",
    "@nuxt/types": "^2.15.8",
    "@nuxt/typescript-build": ">=2.1.0",
    "@nuxtjs/eslint-config-typescript": ">=10.0.0",
    "@nuxtjs/svg": ">=0.4.0",
    "@nuxtjs/tailwindcss": "^5.3.3",
    "@pinia/testing": ">=0.0.14",
    "@tailwindcss/line-clamp": "^0.4.0",
    "@testing-library/jest-dom": ">=5.16.4",
    "@types/google.maps": "^3.49.2",
    "@vue/eslint-config-airbnb": "^6.0.0",
    "@vue/runtime-dom": ">=3.2.39",
    "@vue/test-utils": "1.3.0",
    "@vue/vue2-jest": ">=29.1.0",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": ">=29.0.3",
    "core-js": "^3.24.1",
    "css-loader": "^5.2.0",
    "cypress": ">=10.4.0",
    "eslint": ">=8.20.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-import-resolver-jest": ">=3.0.0",
    "eslint-plugin-nuxt": ">=3.2.0",
    "eslint-plugin-vue": ">=9.3.0",
    "eslint-plugin-vuejs-accessibility": "^1.2.0",
    "flush-promises": ">=1.0.2",
    "jest": ">=29.0.3",
    "jest-context": ">=2.1.0",
    "jest-environment-jsdom": ">=29.0.3",
    "jest-extended": ">=3.1.0",
    "jest-localstorage-mock": ">=2.4.21",
    "jest-transform-stub": ">=2.0.0",
    "jest-when": ">=3.5.1",
    "node-sass": "^6.0.0",
    "sass-loader": "^10.3.1",
    "stylelint": "^13.13.1",
    "stylelint-scss": ">=4.3.0",
    "ts-jest": ">=29.0.1",
    "vue-tsc": ">=0.39.2"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead",
    "not IE 11"
  ]
}

my tsconfig

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "noImplicitAny": false,
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./src/*"
      ],
      "~/*": [
        "./src/*"
      ],
      "@@/*": [
        "./*"
      ]
    },
    "types": [
      "@types/node",
      "@nuxt/types",
      "@pinia/nuxt",
      "jest",
      "jest-extended",
      "@types/google.maps"
    ]
  },
  "exclude": [
    "node_modules",
    "cypress.config.ts",
    "cypress/**/*.ts"
  ]
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

"Uncaught SyntaxError: Cannot use import statement outside ...
There are three ways to solve this:- · 1. The first: In the script, include type=module · 2. The second: In node.js, into...
Read more >
Cannot use import statement outside a module [React ...
In this article, we talked about the SyntaxError: Cannot use import statement outside a module error in TypeScript and JavaScript. This error ...
Read more >
How to fix "cannot use import statement outside a module"
I stumbled on this error: Uncaught SyntaxError: cannot use import statement outside a module while importing a function from a JavaScript file. This...
Read more >
How to solve: cannot use import statement outside a module
How to solve: cannot use import statement outside a module · 1. Transpile your code · 2. Set "type" to "module" in package.json...
Read more >
Javascript Fix Cannot Use Import Statement Outside A Module
STEP #1: Replicate Cannot Use Import Statement Outside A Module Error · STEP #2: Add Type Module Attribute To The Script Tags ·...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found