Storybook fails on eslint errors in react - reactjs

I have configured React, Storybook, Tailwind. everything worked properly. But After I added eslint it breaks storybook for every eslint errors.
.storybook/main.js
const path = require('path');
module.exports = {
stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.#(js|jsx|ts|tsx)'],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/preset-create-react-app',
],
webpackFinal: async (config) => {
config.module.rules.push({
test: /\.css$/,
use: [
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [require('tailwindcss'), require('autoprefixer')],
},
},
],
include: path.resolve(__dirname, '../'),
});
return config;
},
};
Error
[ESLintError:
src/stories/Button.js
Line 2:23: 'prop-types' should be listed in the project's dependencies. Run 'npm i -S prop-types' to add it import/no-extraneous-dependencies
src/stories/Header.js
Line 2:23: 'prop-types' should be listed in the project's dependencies. Run 'npm i -S prop-types' to add it import/no-extraneous-dependencies
src/stories/Page.js
Line 2:23: 'prop-types' should be listed in the project's dependencies. Run 'npm i -S prop-types' to add it import/no-extraneous-dependencies
Line 28:11: " can be escaped with ", “, ", ” react/no-unescaped-entities
Line 28:16: " can be escaped with ", “, ", ” react/no-unescaped-entities
Search for the keywords to learn more about each error.]
WARN Broken build, fix the error above.
WARN You may need to refresh the browser.
error Command failed with exit code 1.

In my case I just wanted to disabled eslint errors during development so
DISABLE_ESLINT_PLUGIN=true start-storybook -p 6006 -s public
did the trick

Thanks for the question, I was struggling with this issue for a couple of hours...
The steps of my investigation are the following:
display the existing Webpack config:
webpackFinal: async (config) => {
console.log(config);
analyse configuration
bail: false,
stats: { preset: 'none', logging: 'error' },
the bail parameter is false what's fine, but preset: 'none' means to show nothing - let's park it, we will need it later
proof: https://webpack.js.org/configuration/stats/#stats-presets
by default the ESLintPlugin throws errors and fails
proof: https://webpack.js.org/plugins/eslint-webpack-plugin/#failonerror
trying to change the parameter failOnError to false, e.g.
new ESLintPlugin({
context: path.resolve(__dirname, '..'),
overrideConfigFile: path.resolve(__dirname, '..', '.eslintrc'),
extensions: ['js', 'jsx'],
files: ['./components', './theme'],
failOnError: false,
})
Now we can see warnings if we change the stats parameters:
webpackFinal: async config => {
config.stats = undefined;
config.plugins.push(

Running storybook with the ESLINT_NO_DEV_ERRORS option also does the trick:
ESLINT_NO_DEV_ERRORS=true npm run storybook
You can also set it and forget it as a storybook environment variable.

this is happened because ESLint is throwing errors instead of warnings!
and storybook can not start with that errors.
you have two ways to solve this problem!!
set 'warn' for all of the rules that you are using in your ESLint config file
use this package https://github.com/bfanger/eslint-plugin-only-warn to change all of rules to 'warn' automatically.

Related

TS Config nested alias for absolute path not working

I'm trying to set up path aliases in my tsconfig.json for a React app bundled with Vite. Here is the relevant part of my tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
...
"paths": {
"*": ["src/*", "node_modules/*"],
"components/*": ["src/components/*"],
"containers/*": ["src/containers/*"],
"pages/*": ["src/constants/*"],
"store/*": ["src/store/*"],
"types/*": ["src/types/*"],
"NestedFolder/*": [
"src/components/NestedFolder/*"
],
}
},
"include": ["src/**/*", "*"]
}
The only issue is with the NestedFolder. When I import this way, everything works:
import { ComponentName } from "components/NestedFolder/types";
However, the nested alias fails:
import { ComponentName } from "NestedFolder/types";
// error
EslintPluginImportResolveError: typescript with invalid interface loaded as resolver
Occurred while linting .../src/components/NestedFolder/canvas/index.ts:1
Rule: "import/namespace"
// error on hover in VS Code
Unable to resolve path to module 'NestedFolder/types'.eslintimport/no-unresolved
I would like to do nested components because I have several folders that are nested 3-4 levels and it would be nice to have a cleaner view of my imports. Is there a way to do this?
You need to install the vite-tsconfig-paths plugin to set up path aliases using TypeScript and Vite.
If nothing changes and you are using VSCode make sure to restart the TypeScript server by pressing Ctrl+Shift+P or Cmd+Shift+P, typing restart, and then selecting the command: TypeScript: Restart TS server
The accepted answer did not work for me. I found that I had to install the following packages:
npm i eslint-plugin-import eslint-import-resolver-alias eslint-import-resolver-typescript
And then add the following configurations, with the important ingredient being strongly-defined alias paths:
const path = require('path');
module.exports = {
root: true, // important to ensure nested eslint scoping in monorepos
plugins: ['#typescript-eslint', 'import'],
extends: [
'airbnb-typescript-prettier',
'plugin:import/typescript'
],
parser: '#typescript-eslint/parser',
parserOptions: {
project: path.join(__dirname, './tsconfig.json'),
tsconfigRootDir: './src',
},
settings: {
"import/parsers": { // add this definition
"#typescript-eslint/parser": [".ts", ".tsx"],
},
'import/resolver': {
alias: {
map: [
// define each alias here
['components', path.join(__dirname, './src/components')],
],
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']
},
typescript: {
project: path.join(__dirname, './tsconfig.json'),
},
},
},
}
I think this could be improved on by harmonizing the aliases between the .eslintrc and vite.config so aliases only need to be defined once, using a tactic like the one defined here: https://stackoverflow.com/a/68908814/14198287
if vite-tsconfig-paths is not working for you. Make sure you didn't install v4.0.0. That version has a bug.
v4.0.1 fix it.
Install with the following:
npm install vite-tsconfig-paths#latest
Should install v4.0.1 at least.
I think this could be improved on by harmonizing the aliases between the .eslintrc and vite.config so aliases only need to be defined once, using a tactic like the one defined here: https://stackoverflow.com/a/68908814/14198287

ERROR in Entry module not found: Error: Can't resolve './src' in

I am trying to add react components to angular1.5 project.
I added to my wepback the path of first component this isnt starting with index.js its just jsx react component.
when I try to run my build I am getting error
WARNING in configuration The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode'
option to 'development' or 'production' to enable defaults for each
environment. You can also set it to 'none' to disable any default
behavior. Learn more: https://webpack.js.org/configuration/mode/
ERROR in Entry module not found: Error: Can't resolve './src'
my code looks like
const path = require('path');
const config = require('./ENVIRONMENT_CONFIG_FOR_GULP/configConstants');
module.exports = {
entry: path.resolve('entryPoint.js'),
mode: 'development',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]},
output: {
filename: config.webpackBundleFileName,
path: path.resolve(config.src, 'modules')
},
devtool: "#source-map"
};
You have two issue in your configuration
First you havent set the mode of webpack yet
So to fix it add below script to your scripts section in package.json
"scripts": {
"prod": "webpack -p --mode=production",
"start": "webpack --mode=development"
}
then run npm run start or npm run prod
Second issue try to use string for your path in this config
path: path.resolve(config.src, 'modules')
change to something like this
output: {
path: path.resolve(__dirname, "wwwroot/dist"),
filename: "[name].js",
publicPath: "/dist/"
},
I find the issue the plugin that I used was changed due to update packages versions:
the current code
let compiler = webpack(webpackConfig);
new webpack.ProgressPlugin().apply(compiler);
return compiler.run(function (err, stats) {

Unable to use the spread operator after ejecting create-react-app

I used create-react-app to create a react application.
After I run eject, I am unable to use the spread operator as follows:
//eslint-disable-next-line
const { children, ...attributes } = this.props; //Line 19
It keeps giving me this error when I run yarn start
Line 19: Parsing error: Unexpected token ..
Webpack Dev Server
I have tried adding all the presets and the transform plugin to both webpack dev server config and .babelrc but no luck
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
presets:['react','es2015','env',"stage-2"],
plugins: ["transform-object-rest-spread"],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
},
},
// "postcss" loader app
And in the babel rc file as well
//.babelrc
{
"presets":["env","react","stage-2"],
"plugins": [
["transform-object-rest-spread", { "useBuiltIns": true }]
]
}
It works fine if I don't eject the script.
So the problem turned out to be eslint.
Webpack config was loading it before babel
Adding parser options fixed it.
{
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
"extends": "airbnb",
"parserOptions":{
"ecmaFeatures": {
"experimentalObjectRestSpread": true
}
}
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
Updated the #babel with this:
npm install #babel/runtime#latest did the work

Ignore or prevent ESLint errors from breaking the build in a React project (create-react-project)

I've recently created a project with create-react-project.
The problem is that, while I'm developing, every time there's a problem with ESLint, the build breaks and doesn't compile the code.
Can I keep the build running while still having ESLint running and reporting errors that I will fix later?
If you want to force ESLint to always emit warnings (that will not stop you build) instead of errors, you need to set emitWarning: true:
{
enforce: 'pre',
include: paths.appSrc,
test: /\.(js|jsx|mjs)$/,
use: [{
loader: require.resolve('eslint-loader'),
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
emitWarning: true, 👈 HERE
},
}],
},
As stated in the docs:
Errors and Warning
By default the loader will auto adjust error reporting depending on eslint errors/warnings counts. You can still force this behavior by using emitError or emitWarning options:
emitError (default: false)
Loader will always return errors if this option is set to true.
emitWarning (default: false)
Loader will always return warnings if option is set to true. If you're using hot module replacement, you may wish to enable this in development, or else updates will be skipped when there's an eslint error.
...
just add DISABLE_ESLINT_PLUGIN=true in your .envfile
cheers !
since eslint-loader is now deprecated and eslint-webpack-plugin is now used in create-react-app check the docs, I was able to solve a similar issue by adding two option to the eslint-webpack-plugin
after ejecting your react app, add these options to the ESLintPlugin options:
new ESLintPlugin({
// Plugin options
extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
context: paths.appSrc,
failOnError: false, <== `This one`
emitWarning: true, <== `And this one`
// ESLint class options
cwd: paths.appPath,
resolvePluginsRelativeTo: __dirname,
baseConfig: {
extends: [require.resolve('eslint-config-react-app/base')],
rules: {
...(!hasJsxRuntime && {
'react/react-in-jsx-scope': 'error'
})
}
}
})
I might be late for the answer but if you add
ESLINT_NO_DEV_ERRORS=true
in the .env file then the error is sorted.
P.S: it works with react script 4.0.3 and above
For people wanting to solve this problem in 2021, you can simply set following in your .env.development file to ignore TypeScript Errors
TSC_COMPILE_ON_ERROR=true
Source: https://create-react-app.dev/docs/advanced-configuration/#:~:text=TSC_COMPILE_ON_ERROR
Also, to ignore ESLint errors, use craco to override eslint-webpack-plugin default configuration to ignore errors in development environment.
const eslintWebpackPlugin = require("eslint-webpack-plugin");
const process = require("process");
module.exports = {
webpack: {
configure: (config) => {
config.plugins.forEach((plugin) => {
if (plugin instanceof eslintWebpackPlugin) {
// Ignore ESLint Errors.
plugin.options.failOnError = process.env.NODE_ENV === "production";
}
});
return config;
},
},
};
Ok I just commented this lines from my webpack config
// {
// test: /\.(js|jsx|mjs)$/,
// enforce: 'pre',
// use: [
// {
// options: {
// formatter: eslintFormatter,
// eslintPath: require.resolve('eslint'),
//
// },
// loader: require.resolve('eslint-loader'),
// },
// ],
// include: paths.appSrc,
// },

Deploying ReactJS app Production

I have finished my ReactJS app and I want to put it in production. I run next command: webpack --progress -p but in chrome F12 I get next error: index.js:1 Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See WebSiteFbReactJs for more details..
It is my webpack.config.js:
'use strict';
const WEBPACK = require('webpack');
const PATH = require('path');
const CopyFiles = require('copy-webpack-plugin');
const BaseName = "/upct";
module.exports = {
resolve: {
extensions: ['', '.js', '.jsx']
},
context: __dirname,
entry: {
app: ['./src/index.jsx']
},
output: {
path: PATH.join(__dirname, '/public'),
/*path: './public',*/
publicPath: BaseName+'/',
filename: 'index.js'
},
devServer: {
host: 'localhost',
port: 3000,
contentBase: PATH.join(__dirname, '/public'),
inline: true,
historyApiFallback: true,
headers: { "Access-Control-Allow-Origin": "*" }
},
module: {
loaders: [
{
test: /(\.js|.jsx)$/,
loader: 'babel',
query: {
"presets": [
"es2015",
"react",
"stage-0"
],
"plugins": [
"react-html-attrs",
"transform-decorators-legacy",
"transform-class-properties"
]
}
}
]
},
plugins: [
new WEBPACK.DefinePlugin({
BASENAME: JSON.stringify(BaseName)
})
]
}
What could this error be?. It is all OK, right? How could I solve this? Thank you.
EDIT: I am getting next error too: DevTools failed to parse SourceMap: http://MYSERVER.com/upct/src/css/bootstrap.css.map
Please add NODE_ENV = 'production' environmental variable to your Webpack build in order to disable debug information and warnings, most of the property type checks and other developer-friendly tools. It will make the app faster but harder to debug. Use this only when deploying to the production.
In your case, in the plugins section just add:
new WEBPACK.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
Please see documentation about optimizing the production build with React, especially Webpack section.
As for the error with the source maps, it seems that the link is broken and returns 404 Not Found error so Chrome can't fetch the original source code mapping for Bootstrap's CSS. That's not a big issue as you probably won't be looking at it's source but that might be a signal that your Webpack build doesn't deploy source maps when building the app. Please add devtool: 'source-map' to your config file in order to produce source maps which will improve the debugging experience on production by translating bundled code to original source files.
UglifyJs will minimize the code size by renaming variables, function names and by other optimization tricks. You can add it to your plugins section of the config file the same way:
new WEBPACK.optimize.UglifyJsPlugin({
compress: {
// suppresses warnings, usually from module minification
warnings: false,
},
}),
There are many possible optimizations, for more information please see this optimization guide.

Resources