Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SyntaxError: Cannot use import statement outside a module. #322

Closed
blopez2010 opened this issue Mar 10, 2020 · 16 comments
Closed

SyntaxError: Cannot use import statement outside a module. #322

blopez2010 opened this issue Mar 10, 2020 · 16 comments

Comments

@blopez2010
Copy link

Hello, when I try to add unit tests to my project, I'm having the following error in the console:

console.log: Jest:   ● Test suite failed to run
[Info]      C:\Code\Web\next-js\node_modules\imask\esm\index.js:1
[Info]      ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import './_rollupPluginBabelHelpers-3c58f0e3.js';
[Info]                                                                                               ^^^^^^
[Info]      SyntaxError: Cannot use import statement outside a module
[Info]        at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
[Info]        at node_modules/react-imask/dist/react-imask.js:2:83
[Info]        at Object.<anonymous> (node_modules/react-imask/dist/react-imask.js:3:3)
[Info]        at Object.<anonymous> (src/components/global-components/form-controls/MaskField.js:8:63)
[Info]        at Object.<anonymous> (src/components/global-components/form-controls/index.js:25:62)
[Info]        at Object.<anonymous> (src/components/component-library/examples/TextFieldExample.js:4:1)
[Info]        at Object.<anonymous> (src/__tests__/components/component-library/examples/TextFieldExample.test.js:9:69)

I have tried several fixes in the web but I can't make it work, have you had this issue before?

This is my package.json

{
  "private": true,
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start -p $PORT",
    "postinstall": "next build",
    "test": "jest --maxWorkers=4 --colors",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage",
    "test:CI": "jest --maxWorkers=4 --colors --coverage --coverageReporters=cobertura --json --outputFile=coverage/testResults.json --ci --reporters=default --reporters=jest-junit",
    "export": "next export"
  },
  "dependencies": {
    "@babel/core": "^7.8.6",
    "@contentful/rich-text-react-renderer": "^13.4.0",
    "@contentful/rich-text-types": "^14.0.1",
    "@fortawesome/fontawesome-pro": "^5.11.2",
    "@fortawesome/fontawesome-svg-core": "^1.2.25",
    "@fortawesome/free-brands-svg-icons": "^5.11.2",
    "@fortawesome/free-solid-svg-icons": "^5.11.2",
    "@fortawesome/pro-light-svg-icons": "^5.11.2",
    "@fortawesome/pro-regular-svg-icons": "^5.11.2",
    "@fortawesome/pro-solid-svg-icons": "^5.11.2",
    "@fortawesome/react-fontawesome": "^0.1.7",
    "@microsoft/applicationinsights-web": "^2.3.1",
    "@optimizely/react-sdk": "^1.0.1",
    "@types/react": "^16.9.14",
    "@zeit/next-css": "^1.0.1",
    "axios": "^0.19.0",
    "babel-plugin-prismjs": "^1.1.1",
    "compression": "^1.7.4",
    "contentful": "^7.10.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "google-map-react": "^1.1.5",
    "isomorphic-unfetch": "^3.0.0",
    "jest-junit": "^10.0.0",
    "js-cookie": "^2.2.1",
    "lodash": "^4.17.15",
    "next": "^9.2.2",
    "next-redux-wrapper": "^3.0.0",
    "nookies": "^2.0.8",
    "prismjs": "^1.17.1",
    "prop-types": "^15.7.2",
    "react": "^16.13.0",
    "react-click-outside": "^3.0.1",
    "react-dom": "^16.12.0",
    "react-imask": "^6.0.3",
    "react-loading-skeleton": "^1.3.0",
    "react-redux": "^7.1.3",
    "redux": "^4.0.4",
    "redux-devtools-extension": "^2.13.8",
    "redux-thunk": "^2.3.0"
  },
  "devDependencies": {
    "babel-jest": "^25.1.0",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "enzyme-to-json": "^3.4.3",
    "husky": "^4.2.3",
    "istanbul-reports": "^3.0.0",
    "jest": "^24.9.0",
    "jest-fetch-mock": "^3.0.1",
    "react-media": "^1.10.0",
    "react-test-renderer": "^16.12.0",
    "redux-mock-store": "^1.5.4"
  }
}

An this my jest.config.js file:

const esModules = ["react-imask", "imask"].join('|');

module.exports = {
  moduleDirectories: ["node_modules", "src", "static", "store"],
  modulePathIgnorePatterns: ["<rootDir>/node_modules/prismjs/plugins/line-numbers"],
  transform: {
    [`(${esModules}).+\\.js$`]: 'babel-jest'
  },
  transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
  testPathIgnorePatterns: [
    "<rootDir>/src/components/component-library",
    "<rootDir>/.next",
    "jest.config.js",
    "next.config.js"
  ],
  collectCoverageFrom: [
    "**/src/**",
    "**/store/**",
    "**/pages/**",
    "!**/__tests__/**",
    "!**/node_modules/**",
    "!**/component-library/**"
  ],
  testEnvironment: "node",
  collectCoverage: true,
  verbose: false,
  automock: false,
  setupFiles: ["./setupTests.js"],
  moduleNameMapper: {
    "functions/(.*)$": "<rootDir>/src/components/Functions/$1",
    "scripts(.*)$": "<rootDir>/src/scripts/$1",
    "^/(.*)$": "<rootDir>/src/$1",
    "^store(.*)$": "<rootDir>/store/$1",
    "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
  },
  coveragePathIgnorePatterns: ["/node_modules/"],
  coverageThreshold: {
    global: {
      branches: 25,
      functions: 20,
      lines: 40,
      statements: 40
    }
  }
};

An I can't make it work, could you help me please?

Thank you!

@uNmAnNeR
Copy link
Owner

seems like imask is not transformed by babel, check your babel.config.js.
jestjs/jest#9395 (comment)
jestjs/jest#4842

@rfestag
Copy link

rfestag commented Mar 16, 2020

I'm a little confused by this...normally babel isn't configured to transpile dependencies. Are you implying that builds should be transpiling react-imask and/or imask? Or am I missing something?

@uNmAnNeR
Copy link
Owner

@rfestag hi. imask ships esm version which is already transpiled by babel, but does not include polyfills. So polyfills should be added separately according environment to run in.
But this issue is about using it with Jest, which does not have support for esm modules, so imask still needs to be transpiled to cjs.

@blopez2010
Copy link
Author

Now I'm getting this error:

[Info]  Started Wallaby.js Core v1.0.863
[Info]  console.log: Jest: FAIL pages/__tests__/_document.test.js
[Info]  console.log: Jest:   ● Test suite failed to run
[Info]      C:\Code\Web\next-js\pages\__tests__\_document.test.js:13
[Info]      import React from 'react';
[Info]      ^^^^^^
[Info]      SyntaxError: Cannot use import statement outside a module
[Info]        at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/node_modules/@jest/transform/build/ScriptTransformer.js:537:17)

The issue is now importing React and make babel-jest to transpile it which is weird since babel is trying to transpile all files within the transform config.

@rfestag
Copy link

rfestag commented Mar 17, 2020

@uNmAnNeR: Thanks for the quick reply. Import shouldn't be a polyfill if it's being transpiled down to es5 though, right? I thought the transpile for that inherently replaced with require statements. Can you point me to a correct import for react-imask? I tried switching to the following, and I get the same error:

import {IMaskInput} from 'react-imask/esm/index';

Originally I tried the following from the examples:

import {IMaskInput} from 'react-imask';

Both of which give me a trace something like this:

import 'imask/esm';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1060:16)
    at Module._compile (internal/modules/cjs/loader.js:1108:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1164:10)
    at Module.load (internal/modules/cjs/loader.js:993:32)
    at Function.Module._load (internal/modules/cjs/loader.js:892:14)
    at Module.require (internal/modules/cjs/loader.js:1033:19)
    at require (internal/modules/cjs/helpers.js:72:18)
...

@k1bs
Copy link

k1bs commented Mar 30, 2020

@uNmAnNeR Hello. I recently had a similar issue using Jest. On a whim, I decided to install version 5.2.1 of your package and it actually resolved the issue. Whatever is causing the react component to break with Jest has just happened since 5.2.1.

@grantiverson
Copy link

For our project, we prefixed the jest command with NODE_ENV=testing and that got it working for us. We updated our test script to run NODE_ENV=testing jest --verbose ./source and now we don't get any errors from imask.

@sem4phor
Copy link

sem4phor commented Apr 8, 2020

I solved it with jest manual mocks (https://jestjs.io/docs/en/manual-mocks). This way you cant test any mask functionality though.

  • Create folder __mocks__ in root
  • Create file vue-imask.js
  • Put Object.create(null) in it

@plinionaves
Copy link

plinionaves commented Jun 19, 2020

If someone is still experiencing this error, the solution is quite simple.

Many npm modules don't pre-compile their source code before publishing, and ES6 code needs to be compiled before it can be run by Jest.

Just add this configuration to the jest.config.js file:

module.exports = {
	...
	transformIgnorePatterns: ['node_modules/(?!(imask)/)']
}

Sources:
jest#9292
StackOverflow
Jest Docs

@vashchukmaksim
Copy link

vashchukmaksim commented Jul 15, 2020

Have the same issue but not with Jest, with SSR build. Nothing works. Tried to include it to babel transpile process - no effect. Any help?

exclude: /node_modules\/(?!(imask)\/).*/,
include: path.join(__dirname, 'node_modules', 'imask')
include: [
    path.resolve('src'),
    path.resolve('node_modules/imask'),
    path.resolve('node_modules/react-imask'),
],

Neither works. I spent 4 hours trying to solve this and no luck.

@MatheusRyuki
Copy link

This error is not fixed, the imask react-plugin dont work at Nextjs (ssr).
image
image

@aryehb
Copy link

aryehb commented Jul 27, 2020

We had this issue with Webpack and babel-loader. iI turned out that the cause was that our Webpack config for babel-loader excluded the entire node_modules, which meant imask wasn't being transpiled.

We changed our config from:

      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
      },

to:

      {
        test: /\.js$/,
        loader: 'babel',
        exclude(modulePath) {
          // Exclude node_modules, but include imask
          return /node_modules/.test(modulePath) && !(/imask/).test(modulePath);
        }
      },

@zeyuri
Copy link

zeyuri commented Jul 31, 2020

For those using Create React App you can add this to your test script in package.json

--transformIgnorePatterns \"node_modules/(?!(imask)/)/\""

@vnt32
Copy link

vnt32 commented Sep 2, 2020

image
I can't figure out what the problem is. WebPack configured with Vue Cli I am using @ uvue / ssr

@vate
Copy link

vate commented Oct 6, 2020

If someone is still experiencing this error, the solution is quite simple.

Many npm modules don't pre-compile their source code before publishing, and ES6 code needs to be compiled before it can be run by Jest.

Just add this configuration to the jest.config.js file:

module.exports = {
	...
	transformIgnorePatterns: ['node_modules/(?!(imask)/)']
}

Sources:
jest#9292
StackOverflow
Jest Docs

This worked for me, thanks!

@jqweryjson
Copy link

image
I can't figure out what the problem is. WebPack configured with Vue Cli I am using @ uvue / ssr

I solved this. Try to add
transformIgnorePatterns: ['node_modules/(?!(vue-masked-input)/)'], into your jest.config.js it is working for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests