Upgrading react-scripts gives error on running react-scripts start - reactjs

After updating react-scripts to version 3.4.0 and on running react-scripts start in windows I get this error:
Must use import to load ES Module: C:\Users\myUser\Desktop\Projects\myproject\frontend\src\setupProxy.js
require() of ES modules is not supported.
require() of C:\Users\myUser\Desktop\Projects\myproject\frontend\src\setupProxy.js from C:\Users\myUser\Desktop\Projects\myproject\frontend\node_modules\react-scripts\config\webpackDevServer.config.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename setupProxy.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\myUser\Desktop\Projects\myproject\frontend\package.json.
And this is the file setupProxy:
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
const proxyTarget = process.env.REACT_APP_API || 'http://localhost:8089';
console.log(`proxying /backend/api/* to ${proxyTarget}/backend/*`);
app.use(proxy('/backend/api', { target: proxyTarget}));
};
Why do I get this error after upgrading react-scripts, and it only displays on windows, if I run the same command on mac, then I don't get this error. How can I fix this for windows?

Related

NextJS getting error on the first npm run dev

I don't know what is going on with my PC but every time I create the NextJS application and run development. It will return this error
error - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[2]!./styles/globals.css
TypeError: Cannot read property 'config' of undefined
(node:20136) [DEP_WEBPACK_MODULE_ISSUER] DeprecationWarning: Module.issuer: Use new ModuleGraph API
(Use `node --trace-deprecation ...` to show where the warning was created)
wait - compiling /_error (client and server)...
error - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[2]!./styles/globals.css
TypeError: Cannot read property 'config' of undefined
at runMicrotasks (<anonymous>)
<w> [webpack.cache.PackFileCacheStrategy] Caching failed for pack: Error: ENOENT: no such file or directory, rename 'C:\laragon\www\bayu-personal-website\.next\cache\webpack\client-development-fallback\0.pack_' -> 'C:\laragon\www\bayu-personal-website\.next\cache\webpack\client-development-fallback\0.pack'
I can't find any cause of this error on my project because it happened after I run yarn create-next-app and yarn dev. Thank you in advance.
Create a postcss.config.js file in the root directory of my NextJS project, fixed it for me.
Example code
module.exports = {
plugins: {
},
}
I manage to create the nextJS project on Users/ directory and it turns out to fix the error. Before that, I created the project outside of Users/ directory (directly on C: and create folder on there). So maybe it was a permission thing that make the project can't run.
I dont really know why, but I installed postcss-loader, css-loader and also created a config file for postcss, postcss.config.js and then the server ran successfully!!
try out that too, I think postcss.config.js is the problem
I was facing the same problem and i fixed it by restarting the IDE AND IT JUST WORK !!
I got a very similar error while updating Tailwind from v2 to v3: TypeError: Cannot read property 'config' of undefined. This was also caused by the postcss.config.js file, as others have suggested. I needed to remove '#tailwindcss/jit': {} from the plugins section. My working config is now:
module.exports = {
plugins: {
autoprefixer: {},
},
}
Run this command in CLI : npm install postcss-flexbugs-fixes postcss-preset-env --save-exact
in postcss.config.js file , write following code:
module.exports={
"plugins" :[
"postcss-flexbugs-fixes",
[
"postcss-preset-env",
{
"autoprefixer": {
"flexbox": "no-2009"
},
"stage": 3,
"features": {
"custom-properties": false
}
}
]
]
}
and you are done ... this worked for me.
Need to create a postcss.config.js file in your root directory if it isnt there from init.
"PostCSS is a tool for transforming styles with JS plugins. These plugins can lint your CSS, support variables and mixins, transpile future CSS syntax, inline images, and more." from postcss Github
postcss.config.js:
module.exports = {
plugins: {
},
}

Environment variables in manifest.json - Chrome Extension

Is it possible to set environment variables in the manifest.json file of a Chrome Extension?
Like wOxxOm said, I used webpack to proccess manifest.json.
In my case, I needed to set version automatically on manifest file.
I added to webpack script:
plugins: [
new CopyWebpackPlugin([
{
from: "public/manifest.json",
to: "manifest.json",
transform(content, path) {
return modify(content)
}
}
]),
]
And the modify function replaces version on file for the parameter:
function modify(buffer) {
var manifest = JSON.parse(buffer.toString());
let argv = process.argv[2];
if (argv) manifest.version = argv.split("=")[1];
let manifest_JSON = JSON.stringify(manifest, null, 2);
return manifest_JSON;
}
So, I build like "yarn build --version=x.x" and webpack do what I need.
PS: if you're going to use this, remember to change:
the manifest.json directory, if necessary;
the value in the modify function, in my case it was version
As the OP has mentioned in her answer, using the copy-webpack-plugin in the webpack.config.js file is the way to go if you're building your Chrome Extension with React. However, if your React app is based on create-react-app, directly editing the webpack.config.js file (which is located in node_modules/react-scripts/config) is not recommended.
In such a case, use craco, which is an npm package that can be used to customize an app based on create-react-app. Here's how you do it:
Install craco into your project using npm i #craco/craco.
Install copy-webpack-plugin as a dev-dependency in your project using npm i --save-dev copy-webpack-plugin.
Let's suppose we're creating a development and a production build of our Chrome Extension. Let's also suppose we've already assigned "version": "0.1.0" in our Chrome Extension's manifest.json. Depending on the build type, we'd like to assign accordingly the version_name field in our Chrome Extension's manifest.json, e.g., "version_name": "0.1.0 dev" for development and "version_name": "0.1.0" for production. In your React app's package.json, introduce two fields (the script names can be whatever you wish) as follows:
"scripts": {
...
"build-dev": "CRX_ENV=dev craco build", // or "set CRX_ENV=dev&& craco build" in the case of Windows
"build-prod": "CRX_ENV=prod craco build", // or "set CRX_ENV=prod&& craco build" in the case of Windows
...
}
Create a new file called craco.config.js in the root of your project. As per your need, do something similar to the following in the craco.config.js file:
const CopyPlugin = require("copy-webpack-plugin")
module.exports = {
webpack: {
plugins: [
new CopyPlugin({
patterns: [
{
from: "public/manifest.json",
to: "manifest.json",
transform(content, path) {
return modifyManifest(content)
},
},
],
}),
],
},
}
function modifyManifest(buffer) {
const manifest = JSON.parse(buffer.toString())
if (process.env.CRX_ENV === "dev") {
manifest.version_name = `${manifest.version} dev`
} else if (process.env.CRX_ENV === "prod") {
manifest.version_name = `${manifest.version}`
}
const manifestJson = JSON.stringify(manifest, null, 2)
return manifestJson
}
Run npm run build-dev. It will create a folder called build in your project root. This build folder is your unpacked Chrome Extension, which you can load into Chrome using the "Load unpacked" button on the chrome://extensions page. Once loaded, you should be able to see 0.1.0 dev as the version name of your Chrome Extension.
Delete the build folder created from the previous step and run npm run build-prod, and repeat the same steps. You should be able to see 0.1.0 as the version name of your Chrome Extension on the chrome://extensions page.

React analyze bundle size

I have a question - how to analyze bundle size?
I want to get informations how bundle files change in case i will push the commit in gitlab.
I was looking for something like danger.js but it probably doesn't support gitlab.
You can use this script to analyze, without ejecting create-react-app
Put analyze.js in root of your project ( where the package.json is located )
npm install progress-bar-webpack-plugin
npm install webpack-bundle-analyzer
analyze.js
process.env.NODE_ENV = 'production';
const webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const webpackConfigProd = require('react-scripts/config/webpack.config')('production');
// this one is optional, just for better feedback on build
const chalk = require('chalk');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const green = text => {
return chalk.green.bold(text);
};
// pushing BundleAnalyzerPlugin to plugins array
webpackConfigProd.plugins.push(new BundleAnalyzerPlugin());
// optional - pushing progress-bar plugin for better feedback;
// it can and will work without progress-bar,
// but during build time you will not see any messages for 10-60 seconds (depends on the size of the project)
// and decide that compilation is kind of hang up on you; progress bar shows nice progression of webpack compilation
webpackConfigProd.plugins.push(
new ProgressBarPlugin({
format: `${green('analyzing...')} ${green('[:bar]')}${green('[:percent]')}${green('[:elapsed seconds]')} - :msg`,
}),
);
// actually running compilation and waiting for plugin to start explorer
webpack(webpackConfigProd, (err, stats) => {
if (err || stats.hasErrors()) {
console.error(err);
}
});
Now simply put node ./analyze.js in the package.json scripts
"scripts": {
.....
"analyze": "node ./analyze.js"
},
after that run npm run analyze
You can also accomplish this using webpack stats json file, supported by create-react-app and webpack-bundle-analyzer.
When running your build with create-react-app, add the --stats flag:
yarn build --stats
This will create a build/bundle-stats.json file, with webpack stats, allowing you to use the webpack-bundle-analyzer CLI to analyze this stats.
yarn run webpack-bundle-analyzer build/bundle-stats.json
reference:
https://www.npmjs.com/package/webpack-bundle-analyzer#user-content-usage-as-a-cli-utility
tested with CRA latest version at the time: v4
You can use and configure webpack-bundle-analyzer library and use it in your React App WITHOUT EJECTING
Add some dependencies by executing npm install --save-dev progress-bar-webpack-plugin webpack-bundle-analyzer
Create a new folder named scripts at the root of your React App.
Create a new file analyze_build_bundle.js in the scripts folder and add the below code in that file
// script to enable webpack-bundle-analyzer
process.env.NODE_ENV = 'production';
const webpack = require('webpack');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const webpackConfigProd = require('react-scripts/config/webpack.config')(
'production'
);
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
webpackConfigProd.plugins.push(new BundleAnalyzerPlugin());
webpackConfigProd.plugins.push(
new ProgressBarPlugin({
format: `analyzing... [:bar] [:percent] [:elapsed seconds] - :msg`,
})
);
// actually running compilation and waiting for plugin to start explorer
webpack(webpackConfigProd, (err, stats) => {
if (err || stats.hasErrors()) {
console.error(err);
}
});
Add the analyze-build-bundle command in your package.json file to run the webpack-bundle-analyzer as below:
"scripts": {
"analyze-build-bundle": "node scripts/analyze_build_bundle.js",
"start": "react-scripts start",
.....
...
}
Now execute command npm run analyze-build-bundle. This will build your app and then start the analyzer local server and you should be able to see the screen as shown in below image

How to transpile node_modules folder using just babel 7?

Trying to unit test reactjs application using mocha but getting error from es6 features (import/export) used inside node_modules folder. The application in question is transpiled using babel but since one of react component is using a module from node_modules its throwing error Syntax Error:Unexpected token export. I am aware that babel ignores node_modules folder by default, but not sure how to approach this. Any help would be appreciated. Thanks.
Test Command :-
"test": "SET NODE_ENV=test&& mocha --require #babel/register --require ignore-styles -r jsdom-global/register \"./src/**/*.test.js\"",
babel.config.js :-
module.exports = function (api) {
const presets = ["react-app"];
const plugins = [
"#babel/plugin-transform-modules-commonjs",
"inline-react-svg"
];
const ignore = [/node_modules/]
api.cache(false);
return {
presets,
plugins,
ignore
}
};
Got it working!. Had to switch from Mocha to Jest since I was using react-app-rewired which was internally configured to use Jest. A small change in config-override.js was needed. Added a jest config with "transformIgnorePatterns": ["node_modules/(?!MODULES_TO_BE_TRANSPILED)"]. Hope it helps others.
try this command, you need to pass ignored directories in command line with --ignored option.
./node_modules/.bin/babel . -d ~/app_compressed/ --ignore node_modules,test,assets,stuff,views,public,test,spec,logs,lib/jasmine_examples,db,routes/api/drafts,**/drafts
Also, make sure to use a babel.config.js file instead of a .babelrc file.
so the config file will look like following.
module.exports = function (api) {
api.cache(true);
return {
babelrcRoots: [
'.',
'./modules/*'
],
ignore: [/node_modules/],
presets: ["#babel/preset-env"]
};
}

How to import environment exported by eslint plugin?

I see that in https://github.com/Gillespie59/eslint-plugin-angular/blob/master/environments.js subsection mocks eslint-plugin-angular declares the inject global variable.
How do I import these environment settings from my application? I tried "extends": "angular" but eslint still complains:
7:14 error 'inject' is not defined no-undef
I tried adding:
"env": {
"angular/mocks": true
}
to the config, but then I got
Environment key "angular/mocks" is unknown
You are getting this error because ESLint can only use environments exposed by plugins and not configs. You have to register eslint-plugin-angular as plugin in your config file:
"plugins": ["angular"],
"env": {
"angular/mocks": true
}
If that still doesn't work, you should run ESLint with --debug flag to see if your config is correctly loaded and environment is applied. You can also run ESLint with --print-config flag followed by a path to some file in your repository to see all of the rules and global variables that ESLint will use when linting that file.

Resources