nextjs v12 swcMinify set to true - reactjs

decided to get rid of my babelrc as the new rust compiler is being promoted and encouraged by vercel. however doing so immediately breaks my build. this is the only thing in my babelrc.
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true, "displayName": true }]]
}
and this is the error after i add
module.exports = {
swcMinify: true
to my next.config.js and i run next build
not sure what i'm missing here since development build works fine, just the build that seems to be breaking on compile. any help would be appreciated
Edit: as requested, this is the entire error
static/chunks/pages/_app-434406ef89d5b351.js from Terser
error: 'eval' and 'arguments' cannot be used as a binding identifier in strict mode
|
97440 | function eval(str) {
| ^^^^
Caused by:
0: failed to parse input file
1: error was recoverable, but proceeding would result in wrong codegen
2: Syntax Error
Error: error: 'eval' and 'arguments' cannot be used as a binding identifier in strict mode
|
97440 | function eval(str) {
| ^^^^
Caused by:
0: failed to parse input file
1: error was recoverable, but proceeding would result in wrong codegen
2: Syntax Error

Create a new file and name it .babelrc (if it does not exist) and add following content:
{
"presets": ["next/babel"]
}
Also open next.config.js and add swcMinify:false

Related

Why is eslint ignoring my strictNullChecks setting?

I am trying to port a large existing JavaScript codebase to TypeScript. I have installed typescript, #typescript-eslint/eslint-plugin and #typescript-eslint/parser as devDependencies and configured the project so that tsconfig.json is used.
My (minimal) tsconfig.json is:
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"alwaysStrict": true,
"strict": true,
"strictNullChecks": true
},
}
Running eslint on an existing .tsx file (correctly) shows some errors:
$ ./node_modules/.bin/eslint ./src/components/JustSomeComponent.tsx
/src/components/JustSomeComponent.tsx
57:75 error Unexpected empty arrow function 'myFunction' #typescript-eslint/no-empty-function
...
✖ 20 problems (8 errors, 12 warnings)
4 errors and 0 warnings potentially fixable with the `--fix` option.
However, I wanted to make sure that strictNullChecks setting was indeed enabled, so I created a new file and made a mistake on purpose:
import React from 'react';
export default class MyComponent extends React.Component {
render(): React.ReactNode {
const x: number = null; // I would expect an error here!
console.log(x);
return null;
}
}
But running the check on this file returns no errors:
$ ./node_modules/.bin/eslint ./src/components/MyComponent.tsx
$
Removing the return type for render() method results in an error, so the checks are performed - I am just not warned about invalid null assignements.
Any idea how I can enable strictNullChecks, or at least how to debug why it is disabled?
strictNullChecks is a TypeScript feature, not an ESLint feature.
As #jonrsharpe commented, strictNullChecks is a compiler setting and does not affect eslint.
The reason I wasn't getting any error was that eslint found errors in other files and prevented build from starting. Once I fixed those, build step indeed failed with an error as expected:
$ npm run build
> myapp#0.0.1 build
> react-scripts build
Creating an optimized production build...
Failed to compile.
/src/components/MyComponent.tsx
TypeScript error in /src/components/MyComponent.tsx(5,11):
Type 'null' is not assignable to type 'number'. TS2322
3 | export default class MyComponent extends React.Component {
4 | render(): React.ReactNode {
> 5 | const x: number = null;
| ^
6 | console.log(x);
7 | return null;
8 | }

Module parse failed: Unexpected token after running eject

Hopefully a quick solution for this one.
I've just done an eject on a React app built in typescript to see if I can get a different problem working.
On trying to compile, I now get this error:
Module parse failed: Unexpected token (27:19)
File was processed with these loaders:
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| }).catch(e => {
| // remove sensitive fields
> if (e.config?.data) delete e.config.data;
| if (e.response?.config?.data) delete e.response.config.data;
| super.analyticsHandler.error(`POST ${url} failed`, e);
My guess is the delete part is causing the problem but I'm not 100%. Maybe I am missing a babel plugin? The project was compiling before the eject.
Please let me know if there are any specific parts of code/config you need to see.
Thanks
EDIT:
This is the babel section in package.json:
"babel": {
"plugins":
[
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-proposal-optional-chaining",
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"babel-plugin-transform-typescript-metadata"
],
"presets": [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript"
]
}

ESLint: 'cy' is not defined (Cypress)

I've just started using Cypress with my React Typescript project. I've gotten some simple tests to run:
describe('settings page', () => {
beforeEach(() => {
cy.visit('http://localhost:3000')
});
it('starts in a waiting state, with no settings.', () => {
cy.contains('Waiting for settings...')
});
it('shows settings once settings are received', () => {
const state = cy.window().its('store').invoke('getState')
console.log(state) // different question: how do I get this to be the state and not a $Chainer?
});
});
It runs in Cypress just fine. But I get Typescript errors in Webstorm, saying that cy is not defined (a TS and ESlint error) and an error on describe saying all files must be modules when the --isolatedModules flag is provided.
I can make it a JS file instead of a TS file, then I still get cy is not defined.
I've tried import cy from 'cypress' but then I get ParseError: 'import' and 'export' may appear only with 'sourceType: module' which is a whole other can of worms (I'm taking baby steps in writing my tests and haven't had to import anything yet...)
/// <reference types="cypress" /> does not work.
Update (sort of)
I've followed instructions here and have made a little progress. To my already very full React webpack.config.dev.js I added the recommended code:
{ // TODO inserted for cypress https://stackoverflow.com/a/56693706/6826164
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
to the end of the list of rules (just before the file loader).
When I do this as well as setting up the plugins/index file as indicated in the article, the cypress "home screen" runs but when I click to open my tests, it takes very many seconds and then shows lots of errors, starting with
integration\settings.spec.ts
This occurred while Cypress was compiling and bundling your test code. This is usually caused by:
A missing file or dependency
A syntax error in the file or one of its dependencies
Fix the error in your code and re-run your tests.
./cypress/integration/settings.spec.ts
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for C:\Users\...\...\front_end\cypress\integration\settings.spec.ts.
# multi ./cypress/integration/settings.spec.ts main[0]
Followed by, actually, a lot of Typescript output such as this:
C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx
[tsl] ERROR in C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx(37,41)
TS2339: Property 'toBeTruthy' does not exist on type 'Assertion'.
C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx
[tsl] ERROR in C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx(41,45)
TS2339: Property 'toBeDefined' does not exist on type 'Assertion'.
Notice that these are now errors for code outside the test files (although perhaps that makes sense). Many of them are for files in which I'm using Jest rather than Cypress, and many errors, as you can see, seem to be related to it inferring an Assertion type on expect that is not Jest, such that it thinks the toEqual matcher is wrong.
All the while, in Webstorm ESLint is still complaining about all my cy and TypeScript is underlining all those Jest assertions mentioned in the output.
This is all with a ts test file. If I rename the file to js, it says the file has no tests.
Any help? I love Cypress but I'm having a hell of a time getting it to work fully!
I got that error after upgrading to cypress version 4+. I installed the eslint-plugin-cypress
https://github.com/cypress-io/eslint-plugin-cypress
and activated it in the extends configuration either in package.json or in separate config file:
"eslintConfig": {
"extends": [
"plugin:cypress/recommended"
]
},
Add .eslintrc.json to cypress directory
In .eslintrc.json
{
"extends": [
"plugin:cypress/recommended"
]
}
I do not install eslint-plugin-cypress, and it fix the problem
Specify cy in eslintrc globals
Answered here
cy is a global variable. Much like location. So really it is window.cy. You can add it to the globals in Eslint. Don't import cy from cypress.
{
"globals": {
"cy": true
}
}
Added that to my .eslintrc and fixed the issue
The Cypress ESLint plugin will get rid of these warnings:
yarn add -D eslint-plugin-cypress (https://github.com/cypress-io/eslint-plugin-cypress)
add .eslintrc to the root of your project with the following:
{
"plugins": ["cypress"],
"extends": ["plugin:cypress/recommended"],
"rules": {
"jest/expect-expect": "off"
}
}
Try.. import cy from "cypress" this solved the problem for me.
at the top of your file put
/// <reference types="cypress" />
or download the official types
source: official cypress intellisense docs
I struggled a lot then this helped...
by adding same line in two files, eslintrc.json and eslintrc.js
(if u have other dependencies in extends, append them as well after it)
extends: ['plugin:cypress/recommended'],
Just add these lines to your tsconfig.json file for e2e tests:
"compilerOptions": {
"types": ["cypress"]
}
This adds support for cypress types.
/* global cy */
import above in your test file
example:
suppose you have login test ("cypress test file ex: cypress/integration/login.js")
I replaced the old style of type referencing,
/// <reference types="cypress" />
with this silly import
import type {} from 'cypress';
And the IDE now both recognizes Cypress's globals while also avoiding the "isolatedModules" issue it has with tsconfig.json
Seems I found a remedy that works (at least) for me. Adding this import to the top of the test:
import _Cypress from "cypress";
relaxes and comforts the ESLint plugin. Actually any name for the import can be used instead of "_Cypress": any that conforms your sense of beauty, does not conflict with anything and starts with underscore (to not provoke ESLint again). Of course, it looks like a kind of voodoo. I don't know why it works and probably there are better ways to present ESLint Cypress's globals, but I don't know them.
add this to jest.config.js
testPathIgnorePatterns: [
'/cypress',
],
Wrap your config object with defineConfig in the cypress.confi.ts file
like so
import { defineConfig } from "cypress";
export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
return config;
},
},
component: {
devServer: {
framework: "create-react-app",
bundler: "webpack",
},
},
});
For me adding .eslintignore in root directory and placing *.cy.js for all my test files was only workaround.
It seems that for the rest of us the working solution really is installing eslint-plugin-cypress and adding:
"eslintConfig": {
"extends": [
"plugin:cypress/recommended"
]
},
but idt didn't helped in my case because this plugin is no longer supported (almost for a year now) so it ended with critical error when combined with cypress-axe.

"fetch" is undefined and "localStorage" is undefined , on using eslint-config-airbnb in react.js

I want to modify my code structure using eslint of airbnb. I have follwed these instruction given in eslint-config-airbnb. After initiating the command
npm run lint, results consists of 'fetch' is not defined and also, 'localStorage' is not defined.
I have gone through this github issue, but still error is shown as the same 'fetch is not defined'. Is there any solutions for it.
No need to add it as an exception, just add this to your .eslintrc and eslint will know what it is:
"env": {
"browser": true
}
You can configure your .eslintrc file with globals.
Add this to your .eslintrc file.
"globals": {
"localStorage": true,
"fetch": true
}
you can try to access to the fetch and localStorage through window object.
window.fetch, window.localStorage

`_Symbol.'for'`: Is that actually valid ES6? Webpack built it from React source

I'm trying to take React 0.14 for a spin before I upgrade it in my project. However, with a simple "hello world" prototype, Webpack is throwing an error:
ERROR in ./~/react/lib/ReactElement.js
Module parse failed: /home/dan/Demos/reactiflux/node_modules/babel-loader/index.js!/home/dan/Demos/reactiflux/node_modules/react/lib/ReactElement.js Line 25: Unexpected string
You may need an appropriate loader to handle this file type.
| // The Symbol used to tag the ReactElement type. If there is no native Symbol
| // nor polyfill, then a plain number is used for performance.
| var REACT_ELEMENT_TYPE = typeof _Symbol === 'function' && _Symbol.'for' && _Symbol.'for'('react.element') || 0xeac7;
|
| var RESERVED_PROPS = {
# ./~/react/lib/ReactMount.js 18:19-44
I do have babel-loader configured, and when I downgrade to React 0.13, everything works. What really stands out to me, is _Symbol.'for', in the middle of the error message.
In react/lib/ReactElement.js on line 21 (not 25), that line looks much more correct, with square brackets around the 'for' key:
var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
I assume that the code shown in the error message is either in an intermediate state during compilation, or is the final compiled output. Does anyone know what could cause Webpack to produce something that looks so wrong? Has anyone successfully used Webpack, Babel and React ~0.14.1 together yet?
update
There is an issue for this: https://github.com/babel/babel/issues/2377
It's closed, but it looks like it came back for me. This was fixed in 5.8.25, but I have 5.8.29 and I still hit the bug.
It appears that the problem has something to do with me including babel runtime. My .babelrc was copied from an older project:
{
"optional": "runtime",
"stage": 0
}
In this little hello-world demo, there is nothing that requires bundling the runtime, so I just removed it, after noticing that https://github.com/DominicTobias/universal-react/, which also uses the same build tools, does not need it. That was the only change I needed to make to get this to build.
My webpack config is super simple:
var path = require("path");
module.exports = {
entry: "./index.js",
output: {
path: path.join(__dirname, "/dist"),
filename: "index.min.js"
},
module: {
loaders: [{
test: /\.js$/,
loader: "babel"
}]
}
};
I guess that's what I get for copying a config file from a more complex project into what was supposed to be a simplest possible demo.
I see that there is a babel-plugin-runtime as well as a babel-runtime on NPM, but when I tried out BPR for the sake of completeness, Babel complains: Module build failed: ReferenceError: The plugin "runtime" collides with another of the same name. Since I don't actually need the runtime, the linked GH repo is a 404, and since this really belongs in the issue trackers after all, this is as far as I am going to take this for now.
No, that is not valid code. That was an issue in Babel project, but it has been fixed in the 6.0 version which was released recently.
I was run into this issue too, and now I have checked this with latest version, and it is works fine. Here is my test steps:
# install Babel and plugins
npm install babel-cli babel-preset-es2015 babel-plugin-transform-runtime
# install React
npm install react
# run babel against problem react file
./node_modules/.bin/babel node_modules/react/lib/ReactElement.js --plugins transform-runtime --presets es2015
It is provides valid output, so the issue seems to be resolved.
And there is good news for you, babel-loader for webpack already supports 6 version of Babel. Check out its docs for details

Resources