Cannot find module 'react' from 'index.js' - (node_modules/jest-resolve/build/index.js:259:17) - node.js

My project creation process (this is a create-react-app typescript version template:
25 npx create-react-app test --template typescript
26 cd test
27 ls
28 npm install --save-dev react-test-renderer
29 npm test
30 npm test
31 node --version
32 npx create-react-app --version
33 npm install antd -g
34 npm test
My Jest version in package-lock.json
"#jest/core": {
"version": "24.9.0",
My node.js version is
v12.19.0
create-react-app version is
npx create-react-app --version
3.4.1
antd version is
antd#4.6.6
file: App.test.tsx testing file
import React from 'react';
import { render } from '#testing-library/react';
import App from './App';
import renderer from 'react-test-renderer';
import MyButton from './components/button';
it('renders a snapshot', () => {
const tree = renderer.create(<App/>).toJSON();
expect(tree).toMatchSnapshot();
});
it('MyButton', () => {
const tree = renderer.create(<MyButton/>).toJSON();
expect(tree).toMatchSnapshot();
});
My antd source file
import React from 'react'
import { Button } from 'antd';
const MyButton = () => {
const [value, setValue] = React.useState('')
// The event type is a "ChangeEvent"
// We pass in "HTMLInputElement" to the input
function onChange(e: React.ChangeEvent<HTMLInputElement>) {
setValue(e.target.value)
}
return <Button></Button>
}
export default MyButton;
When I ran npm test, I got this
FAIL src/App.test.tsx
● Test suite failed to run
Cannot find module 'react' from 'index.js'
However, Jest was able to find:
'components/button.tsx'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].
See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
at Object.<anonymous> (../../../node_modules/antd/lib/affix/index.js:26:37)

Related

installing the proper version of react-native

I want to make a project that contains the Viro package, so that package needs the react-native version 0.65.1 so I tried to downgrade react-native from 0.68.2 to the supported version of the package 0.65.1 when testing the project on expo I get this message
Warning: Invalid version react-native#0.65.1 for expo sdkVersion 45.0.0. Use react-native#0.68.2
Android Bundling failed 1677ms
Unable to resolve module buffer from C:\Users\MrObscure\Desktop\react\Partner\node_modules\safe-buffer\index.js: buffer could not be found within the project or in these directories:
node_modules
If you are sure the module exists, try these steps:
1. Clear watchman watches: watchman watch-del-all
2. Delete node_modules and run yarn install
3. Reset Metro's cache: yarn start --reset-cache
4. Remove the cache: rm -rf /tmp/metro-*
1 | /* eslint-disable node/no-deprecated-api */
> 2 | var buffer = require('buffer')
| ^
3 | var Buffer = buffer.Buffer
4 |
5 | // alternative to using Object.keys for old browsers
and the packages that is used in this project are
import React,{ useRef, useState, useEffect } from "react";
import {I18nManager, ImageBackground,Animated, StyleSheet,TouchableOpacity,Image,Text,TextInput, Alert,ActivityIndicator,ToastAndroid, View } from "react-native";
import AnimatedTypeWriter from 'react-native-animated-typewriter'
import AppLoading from "expo-app-loading";
import { useFonts } from 'expo-font';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { faArrowRightArrowLeft } from "#fortawesome/free-solid-svg-icons";
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { Button,Card,Avatar,ListItem,Icon } from '#rneui/themed';
import { color } from "#rneui/base";
What was the command you ran to downgrade? npm install react-native#0.65.1 would install the specific version you are looking for. Check the pagacke.json file, what version does it say you have? Did you run an npm i after?
What is the expo version? You could manually in the package.json and run expo install.

Vite & Vite-plugin-html-purgeCSS: failed to load config, error during build

I'm using Vite as the build tool for a project and added the plugin "vite-plugin--html-purgecss" to use PurgeCSS. However on build I get the following error:
failed to load config from C:\Users\User Name\Documents\GitHub\project-template\vite.config.js
error during build:
TypeError: htmlPurge is not a function
at file:///C:/Users/User%20Name/Documents/GitHub/project-template/vite.config.js.timestamp-1663917972492.mjs:6:5
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:533:24)
at async loadConfigFromBundledFile (file:///C:/Users/User%20Name/Documents/GitHub/project-template/node_modules/vite/dist/node/chunks/dep-cff57044.js:63470:21)
at async loadConfigFromFile (file:///C:/Users/User%20Name/Documents/GitHub/project-template/node_modules/vite/dist/node/chunks/dep-cff57044.js:63356:28)
at async resolveConfig (file:///C:/Users/User%20Name/Documents/GitHub/project-template/node_modules/vite/dist/node/chunks/dep-cff57044.js:62973:28)
at async doBuild (file:///C:/Users/User%20Name/Documents/GitHub/project-template/node_modules/vite/dist/node/chunks/dep-cff57044.js:45640:20)
at async build (file:///C:/Users/User%20Name/Documents/GitHub/project-template/node_modules/vite/dist/node/chunks/dep-cff57044.js:45629:16)
at async CAC.<anonymous> (file:///C:/Users/User%20Name/Documents/GitHub/project-template/node_modules/vite/dist/node/cli.js:748:9)
Vite.config.js is defined at the root of the project, and am running node 16.17.0. The template project isn't running any frameworks.
I've tried two config files:
import { defineConfig } from 'vite'
import htmlPurge from 'vite-plugin-html-purgecss'
export default defineConfig({
plugins: [
htmlPurge()
]
})
and
import htmlPurge from 'vite-plugin-html-purgecss'
export default {
plugins: [
htmlPurge()
]
}
I had the same issue. I think it's a compatibility issue or an update that no longer supports that plugin. Try running the following:
npm install vite-plugin-purgecss -D
vite.config.js file:
import { defineConfig } from "vite";
import htmlPurge from 'vite-plugin-purgecss';
export default defineConfig({
plugins: [
htmlPurge([htmlPurge()]),
],
});
Let me know if that works for you.

How to export the configuration of `webpack.config.js` using pure ESM?

I'm trying to convert into pure ESM the webpack.config.js
import path from 'path'
import {fileURLToPath} from 'url'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import CopyPlugin from 'copy-webpack-plugin'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import webpack from 'webpack'
var main_config = {
}
var renderer_config = {
}
var config = [
main_config,
renderer_config,
]
export config
I get this error:
yarn start
yarn run v1.22.18
$ yarn run build && ELECTRON_DISABLE_SECURITY_WARNINGS=true electron ./dist/main/main.js
$ npx webpack --config ./webpack.config.js
[webpack-cli] Failed to load '/home/raphy/NEW-Raphy-Template
/webpack.config.js' config
[webpack-cli] SyntaxError: Unexpected token 'export'
at ESMLoader.moduleStrategy (node:internal/modules
/esm/translators:117:18)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:337:14)
at async link (node:internal/modules/esm/module_job:70:21)
I tried also with
export renderer_config, main_config
and with
export renderer_config
export main_config
but still get error
Other info:
node: v16.15.0
O.S. : Ubuntu 20.04 Desktop
npm: v 8.5.5
You will need to export config as default with
export default config
You will also need to update your package.json to set
"type": "module"
or change the extension of the config to .mjs so that node understands this is as es module ( See: https://nodejs.org/api/packages.html#type )

setup webpack config in nextJS (next.config.js)

I'm working with NextJS and using react-data-export plugin to generate xls files.
in the description it says :
This library uses file-saver and xlsx and using
json-loader will do the magic for you.
///webpack.config.js
vendor: [
.....
'xlsx',
'file-saver'
],
.....
node: {fs: 'empty'},
externals: [
{'./cptable': 'var cptable'},
{'./jszip': 'jszip'}
]
but I have no idea how to implement it and got error like this :
The static directory has been deprecated in favor of the public directory. https://err.sh/vercel/next.js/static-dir-deprecated
Defining routes from exportPathMap
event - compiled successfully
> Ready on http://localhost:80 or http://localhost
> Ready on https://localhost:443 or https://localhost
event - build page: /menu_accounting/ReportGross
wait - compiling...
error - ./node_modules/react-export-excel/node_modules/xlsx/xlsx.js
Module not found: Can't resolve 'fs' in '/home/ahmadb/repos/lorry-erp/node_modules/react-export-excel/node_modules/xlsx'
Could not find files for /menu_accounting/ReportGross in .next/build-manifest.json
I had the same problem, the solution for me was this:
Install this packages (if you installed, ignored this)
npm install file-saver --save
npm install xlsx
npm install --save-dev json-loader
Add this to your nextjs.config.js
const path = require('path')
module.exports = {
...
//Add this lines
webpack: (config, { isServer }) => {
// Fixes npm packages that depend on `fs` module
if (!isServer) {
config.node = {
fs: 'empty'
}
}
return config
}
}

unexpected token import when use localize-router in Angular 4 Universal app

I try to build Angular 4 app with server rendering side and language route path. All this base on Angular CLI in 1.5.0-rc1 version.
Everything work OK but I can't solve a problem with language in route.
I have two idea - one to make it like a parameter :lang in URL, but everywhere people advice me to use localize-router plugin. It look very good, but my npm run server can't start properly. In console I get an error:
/home/xxx/Projects/private/angular4-cli-seed/node_modules/localize-router/src/localize-router.config.js:1
(function (exports, require, module, __filename, __dirname) { import { Inject, OpaqueToken } from '#angular/core';
Here is my app-routing.module.ts:
import {NgModule, PLATFORM_ID, Inject, OpaqueToken} from '#angular/core';
import 'zone.js';
import 'reflect-metadata';
import { Routes, RouterModule } from '#angular/router';
import {AboutComponent} from './about/about.component';
import {HomeComponent} from './home/home.component';
import {LocalizeParser, LocalizeRouterModule, LocalizeRouterSettings, ManualParserLoader} from 'localize-router';
import {HttpClientModule, HttpClient} from '#angular/common/http';
import {TranslateService} from '#ngx-translate/core';
import { Observable } from 'rxjs/Observable';
import { Location } from '#angular/common';
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'about',
component: AboutComponent
}
];
export function localizeFactory(translate: TranslateService, location: Location, settings: LocalizeRouterSettings): LocalizeParser {
const browserLocalizeLoader = new ManualParserLoader(translate, location, settings, ['en', 'pl'], 'pl');
return browserLocalizeLoader;
}
#NgModule({
imports: [
RouterModule.forRoot(routes),
LocalizeRouterModule.forRoot(routes, {
parser: {
provide: LocalizeParser,
useFactory: (localizeFactory),
deps: [TranslateService, Location, LocalizeRouterSettings, HttpClient]
}
}),
],
exports: [RouterModule]
})
export class AppRoutingModule {
private static TranslateService: any;
}
Do you have any tips how can I solve it? I found some tips for Webpack (to use exclude list), but I want to use CLI because I don't know Webpack too well.
This problem is connected with library type - it's not a commonjs type, but ES6. More about this problem you can read here on GitHub.
To solve it you can contact the author of library what you want to use in Angular 4 Universal (with Angular CLI). They should recompile it in a proper way.
Another solution (more quick to realize) give me a #sjogren on GitHub. You can use babel.js to recompile library during a building process. To do this you should run:
npm install babel-cli --save
npm install babel-preset-env --save
npm install babel-preset-es2015 --save
and add this code in package.json:
"babel": {
"presets": [
"es2015"
]
},
Finally in package.json you should add to your scripts prestart script with code to recompile the library. In my example:
"scripts": {
"prestart": "node node_modules/babel-cli/bin/babel.js node_modules/localize-router --out-dir node_modules/localize-router --presets es2015"
"start": "......"
}
This worked fine for me, and I don't have an Unexpected Token Import error.

Resources