I'm trying to use FontAwesome with NuxtJS but it doesn't work for unknown reasons.
Here is my package.json:
{
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview"
},
"devDependencies": {
"nuxt": "3.0.0-rc.6",
"sass": "^1.54.0",
"sass-loader": "^13.0.2"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^6.1.2",
"#fortawesome/free-regular-svg-icons": "^6.1.2",
"#fortawesome/free-brands-svg-icons": "^6.1.2",
"#fortawesome/free-solid-svg-icons": "^6.1.2",
"#fortawesome/vue-fontawesome": "^3.0.1",
"#nuxtjs/fontawesome": "^1.1.2"
}
}
Here is my nuxt.config.ts:
import { defineNuxtConfig } from 'nuxt'
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
buildModules: ['#nuxtjs/fontawesome'],
fontawesome: {
icons: {
solid: ['faHome']
}
}
})
Now pages/index.vue:
<template>
<div>
Hello
</div>
</template>
As you can see I'm not even using any icon in this example, yet my app cannot start due to the following error in the Terminal (when I run npm run dev).
ℹ Vite client warmed up in 440ms 12:52:57
ℹ Vite server warmed up in 113ms 12:52:57
✔ Vite server built in 812ms 12:52:58
✔ Nitro built in 178 ms
[h3] [unhandled] H3Error: Cannot read properties of undefined (reading 'component')
at createError (file:///Users/thomasgysemans/Documents/GitHub/vue-portfolio/node_modules/h3/dist/index.mjs:191:15)
at Server.nodeHandler (file:///Users/thomasgysemans/Documents/GitHub/vue-portfolio/node_modules/h3/dist/index.mjs:381:21) {
statusCode: 500,
fatal: false,
unhandled: true,
statusMessage: 'Internal Server Error'
}
I don't understand this error and it seems like I am the only one to have it. Also, I'm new to NuxtJS and Vue.
I am following the documentation of #nuxtjs/fontawesome, and if I understand it well, I'm doing nothing wrong... Well I hope I made a simple mistake that will be solved lol. I really want to use FontAwesome, and it should work as FontAwesome itself provides a documentation on how to use their icons with Vue (but nothing related to NuxtJS).
Edit
Also, the app shows this as plain text, in a black background, but it doesn't show my beautiful "Hello".
{
"statusCode": 404,
"statusMessage": "Not Found",
"stack": []
}
Here is how to setup this
yarn add #fortawesome/fontawesome-svg-core #fortawesome/vue-fontawesome#latest-3
In a new /plugins/fontawesome.js file, put the following
import { library, config } from '#fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '#fortawesome/vue-fontawesome'
import { fas } from '#fortawesome/free-solid-svg-icons'
// This is important, we are going to let Nuxt worry about the CSS
config.autoAddCss = false
// You can add your icons directly in this plugin. See other examples for how you
// can add other styles or just individual icons.
library.add(fas)
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.component('font-awesome-icon', FontAwesomeIcon, {})
})
Inside of nuxt.config.ts
export default defineNuxtConfig({
css: [
'#fortawesome/fontawesome-svg-core/styles.css'
]
})
You should now be able to use it like this
<template>
<div>
<font-awesome-icon icon="fa-solid fa-user-secret" />
</div>
</template>
More info is available here: https://fontawesome.com/docs/web/use-with/vue/use-with#nuxt
Related
I'm using NuxtJS 3 with FontAwesome. I've managed to get it working, but I receive a warning the console of my IDE which says:
[Vue warn]: Component "font-awesome-icon" has already been registered in target app.
Where does it come from? Is this a problem? And how to fix this?
Here is my package.json:
{
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview"
},
"devDependencies": {
"#nuxtjs/google-fonts": "^3.0.0-0",
"nuxt": "3.0.0-rc.6",
"sass": "^1.54.0",
"sass-loader": "^13.0.2"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^6.1.2",
"#fortawesome/free-brands-svg-icons": "^6.1.2",
"#fortawesome/free-regular-svg-icons": "^6.1.2",
"#fortawesome/free-solid-svg-icons": "^6.1.2",
"#fortawesome/vue-fontawesome": "^3.0.1",
"#nuxtjs/fontawesome": "^1.1.2",
"firebase": "^9.9.1"
}
}
My nuxt.config.ts:
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
plugins: [
'~/plugins/fontawesome.ts',
'~/plugins/firebase.client.ts'
],
buildModules: [
'#nuxtjs/google-fonts'
],
googleFonts: {
display: 'swap',
prefetch: true,
preconnect: true,
preload: true,
families: {
Nunito: true,
}
},
css: [
'#fortawesome/fontawesome-svg-core/styles.css',
],
runtimeConfig: {
FIREBASE_API_KEY: process.env.FIREBASE_API_KEY,
},
})
And the fontawesome plugin in ~/plugins/fontawesome.ts:
import { library, config } from '#fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '#fortawesome/vue-fontawesome'
import { fas } from '#fortawesome/free-solid-svg-icons'
import { far } from '#fortawesome/free-regular-svg-icons'
import { fab } from '#fortawesome/free-brands-svg-icons'
import { defineNuxtPlugin } from "nuxt/app";
config.autoAddCss = false
library.add(fas)
library.add(fab)
library.add(far)
export default defineNuxtPlugin((nuxtApp) => {
// This line creates problems with TypeScript whereas it is not raising any runtime error
// #ts-ignore
nuxtApp.vueApp.component('font-awesome-icon', FontAwesomeIcon, {});
});
Several problems:
TypeScript doesn't like calling nuxtApp.vueApp.component() like this because apparently there is no such function declared for 3 arguments given by the FontAwesome documentation
The warning is annoying and I don't find anything that could help me.
My icons do show up (so it looks like this is working despite the warning).
Did I do something wrong?
I'm working on creating a yarn workspace to share code between React and React Native (upcoming blog post once it's completely done!).
The most important part for us is sharing business logic between both platforms. In this case we are using react-query for network requests.
We've created a "Render prop" component for that
import { useAllDevices } from "../../queries/devices";
export interface DeviceListProps {
devices: any[];
isLoading: boolean,
onItemClick?: () => void;
}
export interface DeviceItemListProps {
name: string;
onItemClick?: () => void;
}
export const DeviceListContainer = ({ render }: { render: any }) => {
const { data, isLoading } = useAllDevices();
return (
<>
{render({ devices: data?.devices, isLoading })}
</>
)
}
where useAllDevices is something like this:
export const useAllDevices = () => useQuery('useAllDevices', async () => {
const devicesResponse = await get('/todos');
return {
devices: devicesResponse.data,
};
});
In web, it works like a charm, but I'm getting an error for mobile app. It seems like the problem is with react-query itself because once I put this:
const queryClient = new QueryClient();
const App = () => {
const isDarkMode = false;
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={THEME}>
<SafeAreaView style={backgroundStyle}>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
<Button styleType="primary">hey</Button>
</ScrollView>
</SafeAreaView>
</ThemeProvider>
</QueryClientProvider>
);
};
I get this error
It is working properly and with no problems for React web version
my package.json on the App module is this
{
"name": "#sharecode/app",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest --updateSnapshot",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx"
},
"dependencies": {
"react": "17.0.2",
"react-native": "0.67.3",
"react-native-gesture-handler": "^2.3.0",
"styled-components": "^5.3.3"
},
"devDependencies": {
"#babel/core": "^7.12.9",
"#babel/runtime": "^7.12.5",
"#react-native-community/eslint-config": "^2.0.0",
"#sharecode/common": "1.0.0",
"#testing-library/jest-native": "^4.0.4",
"#testing-library/react-native": "^9.0.0",
"#types/jest": "^27.4.1",
"#types/react-native": "^0.66.15",
"#types/react-test-renderer": "^17.0.1",
"#types/styled-components-react-native": "^5.1.3",
"#typescript-eslint/eslint-plugin": "^5.7.0",
"#typescript-eslint/parser": "^5.7.0",
"babel-jest": "^26.6.3",
"eslint": "^7.14.0",
"get-yarn-workspaces": "^1.0.2",
"jest": "^26.6.3",
"metro-config": "^0.56.0",
"metro-react-native-babel-preset": "^0.66.2",
"nock": "^13.2.4",
"react-test-renderer": "17.0.2",
"ts-jest": "^27.1.3",
"typescript": "^4.4.4"
},
"workspaces": {
"nohoist": [
"react-native",
"react-native/**",
"react",
"react/**",
"react-query",
"react-query/**"
]
},
"resolutions": {
"#types/react": "^17"
},
"jest": {
"preset": "react-native",
"setupFilesAfterEnv": [
"#testing-library/jest-native/extend-expect"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
]
}
}
Main package
{
"name": "#sharecode/common",
"version": "1.0.0",
"main": "index.ts",
"license": "MIT",
"dependencies": {
"axios": "^0.26.0",
"react-query": "^3.34.16",
"styled-components": "^5.3.3"
},
"devDependencies": {
"#types/styled-components": "^5.1.24"
}
}
And web package (working perfectly)
{
"name": "#sharecode/web",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.2",
"#testing-library/react": "^12.1.3",
"#testing-library/user-event": "^13.5.0",
"#types/jest": "^27.4.1",
"#types/node": "^16.11.26",
"#types/react": "^17.0.39",
"#types/react-dom": "^17.0.13",
"react": "17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "^5.0.0",
"typescript": "^4.6.2",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"eslint-config-react-app": "^7.0.0",
"react-app-rewired": "^2.2.1"
}
}
The error seems to be pretty straightforward but I cannot see what's going on
ERROR Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
This error is located at:
in QueryClientProvider (at App.tsx:31)
in App (at renderApplication.js:50)
in RCTView (at View.js:32)
in View (at AppContainer.js:92)
in RCTView (at View.js:32)
in View (at AppContainer.js:119)
in AppContainer (at renderApplication.js:43)
in NuoDoor(RootComponent) (at renderApplication.js:60)
✨ Done in 318.43s.
Also, here is the result of `yarn why react``
javiermanzano#Javiers-MBP app % yarn why react
yarn why v1.22.17
[1/4] 🤔 Why do we have the module "react"...?
[2/4] 🚚 Initialising dependency graph...
[3/4] 🔍 Finding dependency...
[4/4] 🚡 Calculating file sizes...
=> Found "#sharecode/app#react#17.0.2"
info Reasons this module exists
- "_project_##sharecode#app" depends on it
- in the nohoist list ["/_project_/#sharecode/app/react-native","/_project_/#sharecode/app/react-native/**","/_project_/#sharecode/app/react","/_project_/#sharecode/app/react/**","/_project_/#sharecode/app/react-query","/_project_/#sharecode/app/react-query/**"]
info Disk size without dependencies: "356KB"
info Disk size with unique dependencies: "404KB"
info Disk size with transitive dependencies: "432KB"
info Number of shared dependencies: 3
=> Found "react#17.0.2"
info Reasons this module exists
- "_project_##sharecode#web" depends on it
- Hoisted from "_project_##sharecode#web#react"
info Disk size without dependencies: "356KB"
info Disk size with unique dependencies: "404KB"
info Disk size with transitive dependencies: "432KB"
info Number of shared dependencies: 3
✨ Done in 1.17s.
I hope I explained the problem! Any help is appreciated :)
Thank you!
I don't think your problem is related to having mismatching versions of React and the renderer, so we end with 2 options.
Option 1:
3. You might have more than one copy of React in the same app
I'll start covering the 3rd since is the most probable, in this case your program is detecting two reacts.
In your yarn why react you got a react from "_project_##sharecode#app" and "_project_##sharecode#web" Hoisted from "_project_##sharecode#web#react", remember this Hoisted info cuz it's important for solve your problem.
Looking at your package.json you do have the react installed on both. And looking at your workspaces nohoist in "#sharecode/app" you say to don't hoist the react package, but as I said before it is be hoisting!.
So what is the problem?
Well, as I understood and are illustrated at the nohoist documentation you need to put the nohoist config at the package.json in your root "monorepo" (In your case the #sharecode/common).
It will look like this:
{
"name": "#sharecode/common",
...,
"devDependencies": {
...
},
"workspaces": {
"packages": ["packages/*"],
"nohoist": [
...,
"**/react",
"**/react/**",
...
]
}
}
Than, with your package.json working as expected when you run yarn why react you should get something like this:
...
=> Found "#sharecode/app#react#17.0.2"
info Reasons this module exists
- "_project_##sharecode#app" depends on it
- in the nohoist list ["/_project_/**/react-native","/_project_/**/react-native/**","/_project_/**/react","/_project_/**/react/**","/_project_/**/react-query","/_project_/**/react-query/**"]
...
Maybe a found in the "_project_##sharecode#web" too, with other nohoist probably. I didn't checked it myself, but with this correction said above you should be with everything running fine. You can check this and this for further explanation on how it works. But I'm pretty sure that the problem is the nohoist not being in the "root monorepo".
P.S.: I tryed to find what is the reason for using "packages": ["packages/*"], and didn't find out. But I'm deducing that it is to say that you're hoisting everything that aren't in nohoist.
Option 2:
2. You might be breaking the Rules of Hooks
Well, if you couldn't solve your problem with the first option, your problem is related to a hook.
I don't know if it's this your problem, but you're calling a bool in a const and probably trying to change it in some place. Can't you refactor to use a useState(false)?
Also check if you'd called some hook inside loops, conditions or nested funcitons in some of your children, probably the QueryClientProvider if I don't miss understood.
Searching for the Rules of Hooks I found this:
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)
I'm working on a nextjs application and installed bootstrap. The styles work but when I try to import the bootstrap.bundle.js file I get an error
Could not find a declaration file for module 'bootstrap/dist/js/bootstrap'. 'c:/Users/HP/OneDrive/Documents/webapps/nft-marketplace/node_modules/bootstrap/dist/js/bootstrap.js' implicitly has an 'any' type.
This is my pacakage.json
{
"name": "nft-marketplace",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.2",
"#nomiclabs/hardhat-waffle": "^2.0.1",
"#openzeppelin/contracts": "^4.3.1",
"#popperjs/core": "^2.10.2",
"axios": "^0.21.4",
"bootstrap": "^5.0.0-beta3",
"chai": "^4.3.4",
"dropzone": "^5.9.3",
"ethereum-waffle": "^3.4.0",
"ethers": "^5.4.6",
"hardhat": "^2.6.4",
"ipfs-http-client": "^52.0.3",
"next": "11.1.2",
"react": "17.0.2",
"react-dom": "17.0.2",
"web3modal": "^1.9.4"
},
"devDependencies": {
"#types/bootstrap": "^5.1.6",
"autoprefixer": "^10.3.4",
"eslint": "7.32.0",
"eslint-config-next": "11.1.2",
"postcss": "^8.3.6",
"tailwindcss": "^2.2.10"
}
}
This is my app.js file
import "bootstrap/dist/css/bootstrap.css";
import "../styles/globals.css";
import { useEffect } from "react";
import "../styles/app.css";
function MyApp({ Component, pageProps }) {
useEffect(() => {
import("bootstrap/dist/js/bootstrap");
}, []);
return <Component {...pageProps} />;
}
export default MyApp;
I have searched and tried different solutions. I have also installed #types/bootstrap but still didn't work. What am I doing wrong? I need help this issue has me so confused.
this worked for me
useEffect(() => {
typeof document !== undefined
? require('bootstrap/dist/js/bootstrap')
: null
}, [])
If you use bootstrap 5 try to install propperjs
npm install #popperjs/core --save
Here are a couple fixes that seemed to work for me. Make sure #types/bootstrap is installed.
Option 1: Instead of import("bootstrap/dist/js/bootstrap");, try just import("bootstrap");.
Option 2: You can tell typescript where the types are for the "bootstrap/dist/js/bootstrap" module by using the paths option in tsconfig.json. That would look something like this:
{
...
"compilerOptions": {
"paths": {
"bootstrap/dist/js/bootstrap" : ["./node_modules/types/bootstrap"]
}
},
...
}
If you are using Vue Vite and have already downloaded npm i --save-dev #types/bootstrap.
You will try this next step which is to add a line of code in the env.d.ts folder, add declare module "boostrap"
I'm new to react and I'm importing using esmodules but I keep getting an error telling react is undefined. I'm running it through babel and then bundling it with webpack. I've looked at some of the other related questions but none seem to be helping with my problem. Why is it comming up undefined and how can I fix it?
Error:
Uncaught ReferenceError: React is not defined
at Object.<anonymous> (bundle.js:formatted:76)
at n (bundle.js:formatted:11)
at bundle.js:formatted:71
at bundle.js:formatted:72
package.json:
{
"name": "reactTestProject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Brandon Lind",
"license": "MIT",
"devDependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3"
},
"dependencies": {
"#babel/polyfill": "^7.2.5",
"react": "^16.8.4"
}
}
files:
filename: app.js
import Square from "./SquareDiv.js";
let main= document.getElementsByTagName("main")[0];
console.log("wtf")
main.appendChild(<Square/>);
filename: SquareDiv.js
import React from "react";
class Square extends React.Component{
constructor(props){
super(props);
this.state={
isOn: true
}
}
getIsOn(){
let currentState= this.state.isOn;
let pastState= state;
if(currentState===false){
currentState===true;
}
else {
currentState ===false;
}
return pastState;
}
render(){
<div onClick={getIsOn} class="square">this.state.isOn</div>
}
}
export {Square};
babel.config.js:
const presets=[
[
"#babel/preset-env",
{
targets:{
esmodules: true,
edge: 10,
chrome: 30,
safari: 30,
firefox: 30,
opera: 30
}
}
],
[
"#babel/preset-react",
{
pragma: "pragma",
pragmaFrag: "pragmaFrag",
throwIfNamespace: false
}
]
];
module.exports={
presets
};
webpack.config.js:
module.exports={
entry: "./src/app.js",
output:{
filename: "bundle.js"
},
module:{
rules:[
{ test: /\.m?js$/,
exclude: /(node_modules|browsers_components)/,
use:{
loader: "babel-loader",
options: {
presets: ["#babel/preset-env","#babel/preset-react"]
}
}
}
]
}
}
Don't use this syntax import React from "./node_modules/react";.
It will work only for files that are created in the root directory, and your components are likely in src/.
Webpack will resolve everything for you, so you can just use import React from 'react'; everywhere.
Also replace this string: export {Square}; with export default Square
And you can omit .js extension when import, so you can write it this way: import Square from "./SquareDiv";
If you don't want to use default export, you should use import {Square} from "./SquareDiv"
You can read the differences between default and regular exports here
You have a lot of problems in your code snippet. I mentioned some of them in my answer. There are more of them:
Don't use class keyword in JSX, it should be className
Use curly braces to render JS values like this.state.isOn
When you use handlers, don't use it like onClick={getIsOn}, use onClick={() => getIsOn()} and etc.
I suggest you to go through React tutorial which will save your time a lot!
App.js needs to import react. Every file that has JSX in it has to import react.
This particular error is happening because the JSX for Square in app.js is getting transpiled into a React method call, and since you haven’t imported React in app.js, React is not defined.
UPDATE
Also, this will fix a couple other errors...
Change <div onClick={getIsOn} class="square">this.state.isOn</div> to:
return <div onClick={this.getIsOn} className="square">{this.state.isOn}</div>
Not sure why it's complaining on this line:
const wrapper = shallow(<BitcoinWidget {...props} />);
/Users/leongaban/projects/match/bitcoin/src/components/bitcoinWidget.test.js: Unexpected token (17:26)
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
- 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/en/configuration.html
Details:
15 |
16 | describe('when rendering', () => {
>17 | const wrapper = shallow(<BitcoinWidget {...props} />);
18 | ^
19 | it('should render a component matching the snapshot', () => {
20 | const tree = toJson(wrapper);
Entire test:
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
// Local components
import BitcoinWidget from './bitcoinWidget';
const props = {
logo: 'foobar',
coin: {
price: 0
},
refresh: jest.fn()
}
describe('when rendering', () => {
const wrapper = shallow(<BitcoinWidget {...props} />);
it('should render a component matching the snapshot', () => {
const tree = toJson(wrapper);
expect(tree).toMatchSnapshot();
expect(wrapper).toHaveLength(1);
});
});
The component
import React from 'react';
const BitcoinWidget = ({ logo, coin : { price }, refresh }) => {
return (
<div className="bitcoin-wrapper shadow">
<header>
<img src={logo} alt="Bitcoin Logo"/>
</header>
<div className="price">
Coinbase
${price}
</div>
<button className="btn striped-shadow white" onClick={refresh}>
<span>Refresh</span>
</button>
</div>
);
}
export default BitcoinWidget;
And my package.json
{
"name": "bitcoin",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-redux": "^5.0.7",
"react-scripts": "1.1.5",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "yarn run test-jest:update --verbose --maxWorkers=2",
"test-jest:update": "jest src --updateSnapshot",
"test-jest": "jest src"
},
"now": {
"name": "bitcoin",
"engines": {
"node": "8.11.3"
},
"alias": "leongaban.com"
},
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/client/assetsTransformer.js"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
]
},
"devDependencies": {
"enzyme": "^3.4.4",
"enzyme-to-json": "^3.3.4",
"jest": "^23.5.0"
}
}
Add this in your package.json jest config.
"transform": {
"\\.js$": "<rootDir>/node_modules/babel-jest"
},
Let me know if the issue still persists.
For anyone using create-react-app, only certain jest configurations can be changed in package.json when using create-react-app.
I have issues with Jest picking up an internal library, Jest would display 'unexpected token' errors wherever I had my imports from this library.
To solve this, you can change your test script to the below:
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",
For anyone who struggled with this issue and none of the above answers worked for them.
After a long time of searching, I reached for this solution:
edit your jest.config.js to add transformIgnorePatterns
//jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
testMatch: ["**/__tests__/**/*.ts?(x)", "**/?(*.)+(test).ts?(x)"],
transform: {
"^.+\\.(js|ts)$": "ts-jest",
},
transformIgnorePatterns: [
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.js$",
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.ts$",
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.tsx$",
],
}
put the packages that you want to ignore inside [] and separate them by |
in my case [#autofiy/autofiyable|#autofiy/property]
I also encountered the same error while setting up Jest in my React app created using Webpack. I had to add #babel/preset-env and it was fixed. I have also written a blog article about the same.
npm i -D #babel/preset-env
And then add this in "presets" in .babelrc file. E.g.
{
"presets": ["#babel/react", "#babel/env"]
}
https://medium.com/#shubhgupta147/how-i-solved-issues-while-setting-up-jest-and-enzyme-in-a-react-app-created-using-webpack-7e321647f080?sk=f3af93732228d60ccb24b47ef48d7062
I added the jest update to my package.json
"jest": {
"transformIgnorePatterns": [
"node_modules/(?!(<package-name>|<second-package-name>)/)"
]
},
Feel free to remove the |<second-package-name> if not required.
You can also do it as part of your script as mentioned #paulosullivan22
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<package-name>)/)'"
In my case, the issue was that I was importing the original module in the mocked module:
import urlExist from "url-exist";
async function stubbedUrlExist(): Promise<boolean> {
// do something
}
export default stubbedUrlExist;
The solution was to not import url-exist in the url-exist mock. This might have lead to a circular import. Jest was perhaps catching this error in a generic try<>catch block dealing with the loading of modules.
Below works for me.
Create babel.config.js file.
module.exports = {
presets: [
[ '#babel/preset-env', { targets: { esmodules: true } } ],
[ '#babel/preset-react', { runtime: 'automatic' } ],
],
};
I updated some dependencies (react, jest and others), and I also got the error:
Jest encountered an unexpected token - SyntaxError: Cannot use import statement outside a module
I had dev dependencies with needed to be transpiled.
What I did first was start all over:
$ jest --init
A jest.config.js is now generated (before I just had Jest configuration in my package.json).
In the error message under details you can see the reporting module, for me it looked like this:
Details: /<project_root>/node_modules/axios/index.js:1
Adding the following transform ignore in jest.config.js solved my problem:
transformIgnorePatterns: [
"node_modules/(?!axios.*)"
],
The axios module was now nicely transpiled and gave no more problems, hope this helps!
https://jestjs.io/docs/27.x/getting-started
Below works for me
module.exports = {
presets: [
["#babel/preset-env", { targets: { node: "current" } }],
"#babel/preset-typescript", "#babel/react"
]
};
could not get it working with transforms, I ended up mocking the dependency:
Create a file: <path>/react-markdown.js
import React from 'react';
function ReactMarkdown({ children }){
return <>{children}</>;
}
export default ReactMarkdown;
On jest.config.js file add:
module.exports = {
moduleNameMapper: {
'react-markdown': '<path>/mocks/react-markdown.js',
},
};
credits to juanmartinez on https://github.com/remarkjs/react-markdown/issues/635