Trouble-shooting "Cannot use import statement outside a module" - reactjs

I am trying to use puppeteer for e2e testing on a react app. I'd prefer to use TypeScript, so I've tried to start with a file that begins with:
import puppeteer, { Browser, Page } from "puppeteer";
I can't seem to resolve this error, though:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import puppeteer from "puppeteer";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1350:14)
I'm eager to learn, but not sure how to trouble-shoot this.

I don't think Jest supports ES6.
Have you checked Jest docs for support -> https://jestjs.io/docs/ecmascript-modules

Related

Mocking TypeScript imports for Storybook

I am attempting to mock the import of a module for use in Storybook but I can only do it with JavaScript and CJS imports, not TypeScript and ESM. My current webpackFinal contains this
config.resolve.alias['moduleToMock'] = require.resolve('../src/mocks/mockModule')
return config;
This current config doesn't work with TypeScript and will throw an error saying that the mock module can't be found. How can I configure this to work with TypeScript?
In general TypeScript only throws errors when you try to compile the code. If you encounter an error on code execution this is very likely more related to your code rewrite. If the webpackFinal of the Storybook already supports ESM and you need to import the module synchronously then you can create a replacement for the require function like this:
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
...
config.resolve.alias['moduleToMock'] = require.resolve('../src/mocks/mockModule')
Hope it helps.

Serviceworker and cannot use import statement outside a module

I have an react-example of a service worker, with import statements.
Like:
import { clientsClaim } from 'workbox-core';
If I use this code (react) in my service-worker, I get the message:
Uncaught SyntaxError: Cannot use import statement outside a module (at service-worker.js:1:1)
Where is the mistake?
You need to bundle a service worker file that uses ES module imports, as they are not supported in all service worker runtime environments at the moment.
The Workbox documentation has some more examples of this usage. Any bundler that supports ES modules should work; I tend to use esbuild nowadays.

Jest: TypeError: Cannot read property of undefined

Im trying to test my React class, that has import dotnetify from "dotnetify"; import. That works fine, but Jest says, that dotnetify is undefined. If i change to const dotnetify = require("dotnetify");, Jest passes test, but this is silly workaround. How to explain Jest, that dotnetify is not undefined?
Than you in advance.
This cannot be 'explained' to Jest, it's really undefined.
There are several ways to handle CommonJS modules in TypeScript. As explained in this answer, there will be default import in CommonJS packge only if synthetic imports were enabled with esModuleInterop (allowSyntheticDefaultImports) compiler option.
Otherwise it should be done like:
import * as dotnetify from "dotnetify";
Or with TypeScript-specific syntax:
import dotnetify = require("dotnetify")

create-react-app & jest — SyntaxError: Unexpected token import

NOTE: I fixed this by moving all of the code inside my src/nod_modules folder into the src folder directly and deleting src/node_modules as per this short thread: https://github.com/facebook/create-react-app/issues/4241
I am using create-react-app and having trouble running Jest.
When I attempt to import any one of my React components into my test file, I get an error when I yarn test:
Test suite failed to run
.../src/node_modules/common/ErrorMessage.js:1
({"Object.<anonymous>":function(
module,exports,require,__dirname,__filename,global,jest)
{import React from 'react'
^^^^^^
SyntaxError: Unexpected token import
This is what my test file looks like:
// test.test.js
// attempting to import
import ErrorMessage from '../node_modules/common/ErrorMessage.js'
// dummy test
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3)
})
However, the error does not get thrown if I'm at the root of the src file, importing my index.js. At that point, the error gets thrown in the first file that index.js imports. For example:
test.test.js
import index from './index'
index.js
import React from 'react'
import { render } from 'react-dom'
import './style/index.css'
import LoginContainer from './node_modules/user/LoginContainer'
import NewUser from './node_modules/user/NewUser'
// etc.
terminal output
FAIL src/test.test.js
● Test suite failed to run
/Users/hannahmccain/Desktop/DEV/expense-report/fullstack-expense-report/client/src/node_modules/user/LoginContainer.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React, { Component } from 'react'
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
at Object.<anonymous> (src/index.js:11:164)
at Object.<anonymous> (src/test.test.js:3:14)
It seems like, in the context of Jest, Babel isn't able to compile the files in src/node_modules properly. I'm just at a loss as to how to correct that! Any insights would be appreciated.
FYI, Jest is supposed to work out-of-the-box with create-react-app, and I don't want to eject. Without ejecting, I'm unable to make certain changes I've seen recommended elsewhere, such as updating the Jest settings in my package.json.
To follow up with #Himanshu Singh answer, by adding this in my package.json helped me resolved this error.
{
test: react-scripts test --transformIgnorePatterns \"node_modules/(?!ui-core)/\" --env=jsdom
}
The code inside node_modules/user/LoginContainer.js is not a production release (babelified version) as it still has those import statement.
Jest that comes pre-configured with create-react-app, excludes everything inside node_modules from babel-transformation before running tests assuming that the code inside node_modules would be pre-babelified.
And since your module inside node_modules isn't babelified, jest throws error as soon as it encounters import statement.
Solution
1. You must be having a build script for your node_module in use. Try placing the production release of your module inside node_modules.This will do the trick but will also create further issues (as per my experience).
2. Start configuring jest and its dependencies explicitly without ejecting. Essentially by changing your test script to jest --env=jsdom. You will need to install jest, react-dom, babel-transforms-* explicitly and then configure using jest configuration inside package.json.
Here you need to focus on two major configuration option - transformIgnorePatterns and transform.
In short, transform everything and ingnore everything that is already transformed.
Take a look at Jest configuration section for more details.

How to import angular library in reactjs?

I am trying to use a style library from work for building an application for internal use. I am building the application with React, but the only one I can access is an AngularJs library starting with '#SomeStyle'. Is there any way to use the AngularJs library in React?
I tried simply use 'import' in react, the code compiles, but the browser respond with error Uncaught SyntaxError: Unexpected token import.
I use babel loader, which transpile the 'import' syntax in my js file. The project runs, but it crashes when I import the angular style library.
The error comes from the code I imported from angular library, which is added to the bundle.js automatically (I think it is similar to C++ include). From my dev tool I see this line import { CommonModule } from '#angular/common' cause an error.

Resources