Error: 'import' and 'export' may appear only with 'sourceType: module'

See original GitHub issue

Getting following error when trying to configure cucumber with typescript in cypress -

SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'
    at EventEmitter.handler (C:\Users\...\AppData\Local\Cypress\Cache\3.2.0\Cypress\resources\app\packages\server\lib\plugins\util.js:67:29)
    at emitOne (events.js:115:13)
    at EventEmitter.emit (events.js:210:7)
    at ChildProcess.<anonymous> (C:\Users\...\AppData\Local\Cypress\Cache\3.2.0\Cypress\resources\app\packages\server\lib\plugins\util.js:25:29)
    at emitTwo (events.js:125:13)
    at ChildProcess.emit (events.js:213:7)
    at emit (internal/child_process.js:768:12)
    at _combinedTickCallback (internal/process/next_tick.js:141:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

cypress/plugins/index.js -

// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************

// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)
// const cucumber = require('cypress-cucumber-preprocessor').default;
const cucumber = require('cypress-cucumber-preprocessor').default;
const browserify = require('@cypress/browserify-preprocessor');
module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config
  // ---> on('file:preprocessor', cucumber())

  const options = browserify.defaultOptions;

  options.browserifyOptions.plugin.unshift(['tsify']);

  // Or, if you need a custom tsconfig.json for your test files:
  // options.browserifyOptions.plugin.unshift(['tsify', {project: 'path/to/other/tsconfig.json'}]);
  on('file:preprocessor', cucumber(options));
}

cypress/support/index.js -

// ***********************************************************
// This example support/index.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './commands';
require('cypress-xpath');
// Alternatively you can use CommonJS syntax:
// require('./commands')

cypress/integration/login/login.ts -

import { Given, When, Then } from 'cypress-cucumber-preprocessor/steps';

const url = 'http://localhost:4200';
Given('I am logged in', () => {
    cy.visit(url);
    cy.server();
    cy.fixture('authtoken').as('authtokenjson');
    cy.route({
        method: 'POST',
        url: '/oauth/token',
        response: '@authtokenjson'
    }).as('apiAuth');
    cy.fixture('userinfo').as('userinfojson')
    cy.route({
        method: 'GET',
        url: '/oauth/user-info',
        response: '@userinfojson'
    }).as('userInfo');

    cy.get('body').then(($body) => {
        if ($body.find('#userId').length) {
            cy.get('#userId').type('admin');
            cy.get('#password').type('admin');
            cy.get('#login-button').click();
            cy.wait(['@apiAuth', '@userInfo']);
          }
    });
});

cypress/tsconfig.json -

{
    "compilerOptions": {
      "strict": true,
      "baseUrl": "../node_modules",
      "target": "es5",
      "lib": ["es5", "dom"],
      "types": ["cypress", "node"]
    },
    "include": [
      "**/*.ts"     
    ]
  }

Any idea what am I missing here? I followed the following link - link

P.S. -

  1. Please let me know if any other information is required from my end.
  2. I am using latest cypress installer 3.2.0
  3. If I rename the login.ts to login.js, it works fine.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:6
  • Comments:8

github_iconTop GitHub Comments

1reaction
kpturnercommented, Sep 3, 2020

I get this simply by adding import { default as _get } from 'lodash-es/get'; to any typescript file within the cypress setup (and of course adding code to use _get)

0reactions
thunderTheGuncommented, Feb 1, 2022

@lgandecki Hi 😃

Getting following error when trying to configure cucumber with cypress-firebase in cypress. SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' at EventEmitter.handler (/Users/.../Library/Caches/Cypress/7.0.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/util.js:69:27) at EventEmitter.emit (events.js:315:20) at ChildProcess.<anonymous> (/Users/.../Library/Caches/Cypress/7.0.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/util.js:19:22) at ChildProcess.emit (events.js:315:20) at emit (internal/child_process.js:903:12) at processTicksAndRejections (internal/process/task_queues.js:81:21)

cypress/plugins/index.js

/// <reference types="cypress" />
const cucumber = require("cypress-cucumber-preprocessor").default;
const browserify = require("@cypress/browserify-preprocessor");


const admin = require("firebase-admin");
const cypressFirebasePlugin = require("cypress-firebase").plugin;

/**
* @type {Cypress.PluginConfig}
*/

module.exports = (on, config) => {

const configJson = require(`../testConfigs/testConfigInfo.json`);
config.baseUrl = configJson[config.env.testbed]["baseUrl"];
const options = browserify.defaultOptions;
options.browserifyOptions.transform[1][1].babelrc = true;


on('file:preprocessor', cucumber(options));

on("before:browser:launch", (browser = {}, launchOptions) => {
 if (browser.name === "chrome") {
   launchOptions.args.push("--disable-extensions"); //https://github.com/cypress-io/cypress/issues/5969
   launchOptions.args.push("--window-size=1920,1080"); //https://github.com/cypress-io/
   return launchOptions;
 }
 return launchOptions;
});

const extendedConfig = cypressFirebasePlugin(on, config, admin);


 return extendedConfig;
};

/Users/…/git/cypress-e2e-test/cypress/support/commands/loginBackground.js

  
   /// <reference types="cypress" />

import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
import 'firebase/compat/database';
import 'firebase/compat/firestore';


// const admin = require("firebase-admin");

import { attachCustomCommands } from 'cypress-firebase';


// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const fbConfig = {
   apiKey: "xxxxxxxxxxxx",
   authDomain: "xxxxxx-test.firebaseapp.com",
   databaseURL: "https://xxxxxxxxx",
   projectId: "xxxxxxxx-test",
   storageBucket: "xxxxxxxx-test.appspot.com",
   messagingSenderId: "xxxxxxxxxx",
   appId: "xxxxxxxxxxxxxx",
   measurementId: "xxxxxxxxxx"
 };


 firebase.initializeApp(fbConfig);
 attachCustomCommands({ Cypress, cy, firebase });

Cypress.Commands.add("loginBackground", (uid, baseUrl) => {

 cy.login(uid);
 cy.visit(baseUrl);

 });

tsconfig.json

{
    "compilerOptions": {
      "strict": true,
      "baseUrl": "../node_modules",
      "target": "es5",
      "lib": ["es5", "dom"],
      "types": ["cypress"]
    },
    "include": [
      "**/*.ts"
    ]
  }

/Users/…/git/cypress-e2e-test/cypress/support/commands/index.js

import '../commands/loginWithCredentials';
import '../commands/loginBackground';

Any idea please why still getting this, I tried theses steps already : https://stackoverflow.com/a/60017105

+1, have the same issue

Read more comments on GitHub >

github_iconTop Results From Across the Web

'import' and 'export' may appear only with 'sourceType: module ...
In my case, I was getting this error with browserify and babelify when trying to compile JS files that imported TypeScript files, e.g....
Read more >
'import' and 'export' may appear only with 'sourceType: module ...
I get this error since the most recent update. is it possible there this is missing somewhere in the package?
Read more >
JavaScript : SyntaxError: 'import' and 'export' may appear only ...
JavaScript : SyntaxError: ' import' and 'export ' may appear only with 'sourceType : module ' - Gulp ... Your browser can't play...
Read more >
Solved: Bundle Error: 'import' and 'export' may appear onl...
Bundle Error: 'import' and 'export' may appear only with 'sourceType: ... But I meet an error after I install an es6 modules( @antv/x6...
Read more >
'import' and 'export' may appear only with 'sourceType: module ...
ParseError : 'import' and 'export' may appear only with 'sourceType: module' It happens just after the npm initialization and Budo installation. ...
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