A few days ago I decide to migrate frontend application to Svelte from Vanilla JS (specific reasons).
And at first I decided to configure eslint config. I spent about 3 hours to find an answer of how to integrate svelte into eslint and I didn't find nothing besides this plugin
Here is my eslint config
module.exports = {
extends: ['eslint:recommended', 'prettier'],
parserOptions: {
ecmaVersion: 2019,
sourceType: 'module'
},
env: {
es6: true,
browser: true
},
plugins: [ 'svelte3' ],
overrides: [
{
files: '*.svelte',
processor: 'svelte3/svelte3'
}
],
globals: {
"module": true,
"process": true,
},
rules: {
// ...
},
settings: {
// ...
}
};
Here is dev. dependencies of package.json:
Where is contains my svelte components:
I have non formatted code:
And what tell me eslint:
After eslint . and eslint . --fix commands the code of svelte component still non formatted
I'm sure that I'm doing something wrong, hope on your help.
To use eslint with svelte 3, all you have to do is :
npm install \
eslint \
eslint-plugin-import \
eslint-plugin-node \
eslint-plugin-promise \
eslint-plugin-standard \
eslint-plugin-svelte3 \
--save-dev
Add this script in package.json :
"scripts": {
"lint": "eslint . --ext .js,.svelte --fix"
},
And add a file .eslintrc.js next to the package.json file :
module.exports = {
parserOptions: {
ecmaVersion: 2019,
sourceType: 'module'
},
env: {
es6: true,
browser: true,
node: true
},
extends: [
'eslint:recommended'
],
plugins: [
'svelte3'
],
ignorePatterns: [
'public/build/'
],
overrides: [
{
files: ['**/*.svelte'],
processor: 'svelte3/svelte3'
}
],
rules: {
// semi: ['error', 'never'] // uncomment if you want to remove ;
},
settings: {
// ...
}
}
Then you can run npm run lint to fix your files.
ESLint (and linters in general) are good for finding and potentially fixing things that violate certain rules, but ESLint isn't primarily a formatting tool.
To format Svelte files automatically, you'll have better luck with Prettier and the Svelte plugin for Prettier.
If you're using Visual Studio Code, you can install the Svelte for VS Code plugin which will be able to format your files automatically when you save them (assuming you have formatOnSave turned on).
I assume you are using VSCode by looking at your screenshots. At the documentation's page of the plugin you mention, there's an explanation of how to configure it in your code editor. ( https://github.com/sveltejs/eslint-plugin-svelte3/blob/master/INTEGRATIONS.md )
You'll need the ESLint extension installed.
Unless you're using .html for your Svelte components, you'll need to configure files.associations to associate the appropriate file extension with the html language. For example, to associate .svelte, put this in your settings.json:
{
"files.associations": {
"*.svelte": "html"
}
}
Then, you'll need to tell the ESLint extension to also lint files with language html and to enable autofixing where possible. If you haven't adjusted the eslint.validate setting, it defaults to [ "javascript", "javascriptreact" ], so put this in your settings.json:
{
"eslint.validate": [
"javascript",
"javascriptreact",
{
"language": "html",
"autoFix": true
}
]
}
If you are using an extension that provides Svelte syntax highlighting, don't associate *.svelte files with the html language, and instead enable the ESLint extension on "language": "svelte".
Reload VS Code and give it a go!
Related
I'm switching my TypeScript project to a (pnpm) monorepo and have troubles getting tests to run properly. I have a jest.config.js that uses a custom testEnvironment that's written in TypeScript as well. However, ever since I moved the specific project into my packages directory for the monorepo restructuring, jest throws an Error and doesn't run any tests:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\workspaces\repos\the-monorepo\packages\testproject\source\testtools\jsdom-environment-global.spec.ts
I tried it with #swc/jest as well as with ts-jest, had a look at How to use TypeScript in a Custom Test Environment file in Jest? (which makes me think "why did this ever work?") and, for whatever reason, it worked fine yesterday. I cleaned jest cache and reinstalled all node_modules to no avail. I also found answers related to "type": "module" in package.json, but this doesn't apply to my package. It's not an ESM.
Here's how the jest.config.js looks like:
/** #type {import('#jest/types').Config.InitialOptions} */
const config = {
silent: true,
testEnvironment: "<rootDir>/source/testtools/jsdom-environment-global.spec.ts",
roots: [
"<rootDir>/source"
],
maxWorkers: "50%",
transform: {
"^.+\\.(t|j)s$": ["#swc/jest", {
sourceMaps: "inline",
module: {
strict: false,
strictMode: false
},
jsc: {
target: "es2021",
parser: {
syntax: "typescript",
dynamicImport: true
}
}
}]
},
transformIgnorePatterns: [
"node_modules"
],
testMatch: [
"**/*/*.spec.ts",
"**/*/*.test.ts",
"!**/playwright-tests/**",
"!**/playwright-tests-smoke/**"
],
moduleFileExtensions: ["ts", "js", "node", "json"],
reporters: [
"default"
],
globals: {
self: {},
navigator: {},
jasmine: {},
__UNIT__: true
},
coverageDirectory: "test-results",
collectCoverage: false,
collectCoverageFrom: [
"./source/**/*.ts"
],
coveragePathIgnorePatterns: [
"/\\.spec\\.ts$/i",
"/.*node_modules.*/",
"/.*testtools.*/"
],
coverageReporters: [
"lcov", "cobertura"
],
coverageProvider: "v8",
resetMocks: true,
restoreMocks: true,
resetModules: true,
setupFilesAfterEnv: [
"jest-extended/all",
"<rootDir>/source/testtools/setup.spec.ts"
],
testPathIgnorePatterns: [
"<rootDir>/source/testtools/",
"<rootDir>/source/smoke-tests/",
"<rootDir>/source/performance-tests/",
"<rooDir>/source/playwright-tests/",
"<rooDir>/source/playwright-tests-smoke/"
],
moduleNameMapper: {
"^#test-helpers": "<rootDir>/source/testtools/index.spec.ts",
"^#test-tools/(.*)": "<rootDir>/source/testtools/$1",
'^(\\.{1,2}/.*)\\.js$': '$1'
}
};
module.exports = config;
Why is jest not able to parse the testEnvironment if it's a TypeScript file?
I found the issue: there seems to be some confusion around the transformer not being applied to ESM files. In my case, the jsdom-environment-global.spec.ts imported an ESM module from a different package within my monorepo. This import triggers an exception because jest tries to import it via require(), which is caught and then again imported via dynamic imports. This dynamic import then throws the exception that ts is an unknown exception. I'm not sure why these files haven't been transformed, but as of How to use TypeScript in a Custom Test Environment file in Jest? this seems to be normal.
Bottom line: don't import from ESM files within your jest testEnvironment module.
I have worked on a vue project which I created using vue cli. Because of this, eslint is also included in the project. Up until now I haven't done much with eslint. If I understood correctly, eslint helps with stylistic errors, semantic errors etc in the code to identify potential problems.
I only rarely used // eslint-disable-next-line if there was e.g. a console.log clashing with the rules.
Now I wanted to include some new javascript code into the project. This code comes from someone else, so I cloned the repo and then just imported it in my main.js via a relative path to the folder/file that I have cloned. I think this was okay. However now I get some problems with eslint as the imported file has no config for eslint.
This is the exact error originating from the import:
Module build failed (from ./node_modules/eslint-loader/index.js):
Error: No ESLint configuration found
I am not sure what to do now, even though I already searched for the error.
I only saw some config for eslint in the package.json, I think. If it would help to have its content or something else, please say so and I will add it!
How can I tackle this problem? Thanks in advance!
This might be a long shot, but this is the .eslintrc.js file I shove into all my react projects at the root directory to get rid of that error. You'll want to change some of the settings but this is the basic structure.
module.exports = {
parser: 'babel-eslint',
env: {
browser: true,
commonjs: true,
es6: true,
node: true,
jest: true,
},
parserOptions: {
ecmaVersion: 2020,
ecmaFeatures: {
jsx: true,
},
sourceType: 'module',
},
plugins: ['react', 'react-hooks'],
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
'plugin:json/recommended',
'prettier',
],
settings: {
react: {
version: 'detect',
},
},
rules: {
'react/prop-types': ['off'],
'react/no-unescaped-entities': ['error', { forbid: ['>', '}'] }],
},
};
Recently Facebook's Create React App (CRA) released a new feature which allows you to extend their base ESLint rules.
We recognise that in some cases, further customisation is required. It
is now possible to extend the base ESLint config by setting the
EXTEND_ESLINT environment variable to true.
Setting Up Your Editor
Here is the example given but with no detail such as filename or what "shared-config" is.
{
"eslintConfig": {
"extends": ["react-app", "shared-config"],
"rules": {
"additional-rule": "warn"
},
"overrides": [
{
"files": ["**/*.ts?(x)"],
"rules": {
"additional-typescript-only-rule": "warn"
}
}
]
}
}
The feature is enabled by added an environment variable.
EXTEND_ESLINT=true
but on the documentation page it also doesn't give any information how to use it - Advanced configuation
I've added their example code to my build in a file called .eslintrc.json but I get a build error:
"Error: ESLint configuration in .eslintrc.json is invalid: - Unexpected top-level property "eslintConfig"."
Has anyone got this working? Does the file need to export a module?
While unclear from the Create-React-App documentation, the example they give is as if the project's ESLint configuration was inside the eslintConfig property of the package.json file.
You need to configure ESLint as described in its documentation. So if you choose the .eslintrc.json way, it must be a valid ESLint configuration file, which doesn't have a eslintConfig property.
The only things that matter in the example are:
they're extending from "react-app" before any other configuration
any additional rule is set to "warn" to avoid stopping the project from building
if using TypeScript, place the specific TS related configuration in the "overrides" section.
A simple .eslintrc.js (notice the extension) configuration file for a CRA project using TypeScript could be as follows:
const defaultRules = [
'react-app',
'eslint:recommended',
// any other plugins or custom configuration you'd like to extend from.
];
module.exports = {
parser: '#typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
env: {
browser: true,
node: true,
es6: true,
jest: true,
},
extends: defaultRules,
rules: {
'array-callback-return': 'warn',
'consistent-return': 'warn',
'default-case': 'warn',
// etc.
},
overrides: [
{
files: ['**/*.ts', '**/*.tsx'],
plugins: ['#typescript-eslint'],
extends: [
...defaultRules,
'plugin:#typescript-eslint/recommended',
// any other TypeScript specific config (from a plugin, or custom)
],
rules: {
'#typescript-eslint/no-explicit-any': 'warn',
'#typescript-eslint/no-unused-vars': 'warn',
'#typescript-eslint/no-unused-expressions': 'warn',
// etc.
},
},
],
settings: {
react: {
// React version. "detect" automatically picks the version you have installed.
version: 'detect',
},
},
};
I've installed the ESlint by following these steps: https://travishorn.com/setting-up-eslint-on-vs-code-with-airbnb-javascript-style-guide-6eb78a535ba6
Now, my ESlint is working from the terminal, but errors/warnings are not displaying in the code window, here is my project structure and how it is looks like:
and my eslintrc configs:
module.exports = {
env: {
browser: true,
commonjs: true,
es6: true,
node: true,
},
extends: [
'airbnb-base',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parserOptions: {
ecmaVersion: 2018,
},
rules: {
},
};
Why it couldn't show errors in the editor?
I ran into this recently, and fixed it by changing my .eslintrc.js file to just .eslintrc (JSON object only, no comments, everything quoted right, no extension). After restarting VSCode it picked up the file properly and gave me linter errors in VSCode.
for me it's work !
setting.json add this
"eslint.validate": [
"vue",
"html",
"javascript",
"typescript",
"javascriptreact",
"typescriptreact"
]
https://linuxpip.org/eslint-not-working-in-vscode/
I followed all the advice and still had issues. I am using Typescript + YARN 2 (w\ PnP).
The error I was receiving was Failed to load the ESLint library for the document [filename].ts
What fixed it for me was that I needed to create some editor SDKs and settings with the command:
yarn dlx #yarnpkg/sdks vscode.
My .vscode/settings.json for eslint looks like:
"eslint.enable": true,
"eslint.packageManager": "yarn",
"eslint.alwaysShowStatus": true,
"eslint.validate": [
"html",
"javascript",
"typescript",
"javascriptreact",
"typescriptreact"
],
"eslint.nodePath": ".yarn/sdks"
The command above added "eslint.nodePath": ".yarn/sdks"
I found this here (I followed this and this to get there).
I'm attempting to use the ESLint linter with the Jest testing framework.
Jest tests run with some globals like jest, which I'll need to tell the linter about; but the tricky thing is the directory structure, with Jest the tests are embedded with the source code in __tests__ folders, so the directory structure looks something like:
src
foo
foo.js
__tests__
fooTest.js
bar
bar.js
__tests__
barTest.js
Normally, I'd have all my tests under a single dir, and I could just add an .eslintrc file there to add the globals... but I certainly don't want to add a .eslintrc file to every single __test__ dir.
For now, I've just added the test globals to the global .eslintrc file, but since that means I could now reference jest in non-testing code, that doesn't seem like the "right" solution.
Is there a way to get eslint to apply rules based on some pattern based on the directory name, or something like that?
The docs show you are now able to add:
"env": {
"jest/globals": true
}
To your .eslintrc which will add all the jest related things to your environment, eliminating the linter errors/warnings.
You may need to include plugins: ["jest"] to your esconfig, and add the eslint-plugin-jest plugin if it still isn't working.
ESLint supports this as of version >= 4:
/*
.eslintrc.js
*/
const ERROR = 2;
const WARN = 1;
module.exports = {
extends: "eslint:recommended",
env: {
es6: true
},
overrides: [
{
files: [
"**/*.test.js"
],
env: {
jest: true // now **/*.test.js files' env has both es6 *and* jest
},
// Can't extend in overrides: https://github.com/eslint/eslint/issues/8813
// "extends": ["plugin:jest/recommended"]
plugins: ["jest"],
rules: {
"jest/no-disabled-tests": "warn",
"jest/no-focused-tests": "error",
"jest/no-identical-title": "error",
"jest/prefer-to-have-length": "warn",
"jest/valid-expect": "error"
}
}
],
};
Here is a workaround (from another answer on here, vote it up!) for the "extend in overrides" limitation of eslint config :
overrides: [
Object.assign(
{
files: [ '**/*.test.js' ],
env: { jest: true },
plugins: [ 'jest' ],
},
require('eslint-plugin-jest').configs.recommended
)
]
From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724
You can also set the test env in your test file as follows:
/* eslint-env jest */
describe(() => {
/* ... */
})
To complete Zachary's answer, here is a workaround for the "extend in overrides" limitation of eslint config :
overrides: [
Object.assign(
{
files: [ '**/*.test.js' ],
env: { jest: true },
plugins: [ 'jest' ],
},
require('eslint-plugin-jest').configs.recommended
)
]
From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724
As of 2021, I think the correct way or at least the one that works is to install #types/jest and eslint-plugin-jest:
npm i -D eslint-plugin-jest #types/jest
And adding the Jest plugin into .eslintrc.js with the overrides instruction mentioned by #Loren:
module.exports = {
...
plugins: ["jest"],
...
overrides: [
{
files: ["**/*.test.js"],
env: { "jest/globals": true },
plugins: ["jest"],
extends: ["plugin:jest/recommended"],
},
],
...
};
This way you get linting errors in your source files as well as in test files, but in test files you don't get linting errors for test and other Jest's functions, but you will get them in your source files as they will appear as undefined there.
I solved the problem REF
Run
# For Yarn
yarn add eslint-plugin-jest -D
# For NPM
npm i eslint-plugin-jest -D
And then add in your .eslintrc file
{
"extends": ["airbnb","plugin:jest/recommended"],
}
some of the answers assume you have eslint-plugin-jest installed, however without needing to do that, you can simply do this in your .eslintrc file, add:
"globals": {
"jest": true,
}
First install eslint-plugin-jest
Running:
yarn add eslint-plugin-jest or npm install eslint-plugin-jest
Then edit .eslintrc.json
{
"env":{
"jest": true
}
}
As of ESLint V 6 (released in late 2019), you can use extends in the glob based config as follows:
"overrides": [
{
"files": ["*.test.js"],
"env": {
"jest": true
},
"plugins": ["jest"],
"extends": ["plugin:jest/recommended"]
}
]
Add environment only for __tests__ folder
You could add a .eslintrc.yml file in your __tests__ folders, that extends you basic configuration:
extends: <relative_path to .eslintrc>
env:
jest: true
If you have only one __tests__folder, this solution is the best since it scope jest environment only where it is needed.
Dealing with many test folders
If you have more test folders (OPs case), I'd still suggest to add those files. And if you have tons of those folders can add them with a simple zsh script:
#!/usr/bin/env zsh
for folder in **/__tests__/ ;do
count=$(($(tr -cd '/' <<< $folder | wc -c)))
echo $folder : $count
cat <<EOF > $folder.eslintrc.yml
extends: $(printf '../%.0s' {1..$count}).eslintrc
env:
jest: true
EOF
done
This script will look for __tests__ folders and add a .eslintrc.yml file with to configuration shown above. This script has to be launched within the folder containing your parent .eslintrc.
Pattern based configs are scheduled for 2.0.0 release of ESLint. For now, however, you will have to create two separate tasks (as mentioned in the comments). One for tests and one for the rest of the code and run both of them, while providing different .eslintrc files.
P.S. There's a jest environment coming in the next release of ESLint, it will register all of the necessary globals.
I got it running after spending some time trying out different options. Hope this helps anyone else getting stuck.
.eslintrc.json (in root project folder):
{
"env": {
"browser": true,
"es2021": true,
"jest/globals": true
},
"extends": [
"standard",
"plugin:jest/all"
],
"parser": "#babel/eslint-parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
"jest/no-hooks": [
"error",
{
"allow": [
"afterEach",
"beforeEach"
]
}
]
},
"plugins": [
"jest"
]
}
Empty .babelrc (in root project folder):
{}
.package.json (in root project folder):
{
"scripts": {
"test": "jest",
"lint": "npx eslint --format=table .",
"lintfix": "npx eslint --fix ."
},
"devDependencies": {
"#babel/core": "^7.15.0",
"#babel/eslint-parser": "^7.15.0",
"aws-sdk-mock": "^5.2.1",
"eslint": "^7.32.0",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-import": "^2.24.0",
"eslint-plugin-jest": "^24.4.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.1.0",
"jest": "^27.0.6"
}
}
VS Code settings.xml (editor configuration: enables auto fix on save + babel parser):
"eslint.alwaysShowStatus": true,
"eslint.format.enable": true,
"eslint.lintTask.enable": true,
"eslint.options": {
"parser": "#babel/eslint-parser"
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": [
"javascript"
]
In your .eslintignore file add the following value:
**/__tests__/
This should ignore all instances of the __tests__ directory and their children.