ESLint linting my Typescript files correctly - node.js

I have .js files ( src/client/...) and .ts files ( src/server/.. )
I installed the following packages :
package.json
"eslint": "^5.11.1",
"eslint-config-airbnb-base": "^13.1.0",
"eslint-config-typescript": "^1.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-typescript": "^0.14.0",
....
"typescript": "^3.0.3",
"typescript-eslint-parser": "^21.0.2",
And I defined the following aslant config in package.json
"eslintConfig": {
"extends": ["airbnb-base", "eslint:recommended", "typescript"],
"env": { "es6": true, "browser": true },
"parserOptions": { "parser": "typescript-eslint-parser" },
"plugins": ["typescript"],
"rules": {
"no-unused-vars": ["error", { "vars": "all", "args": "after-used", "ignoreRestSiblings": false }],
"no-var": ["off"],
"one-var": ["off"],
"prefer-destructuring": ["error", { "object": false, "array": false } ],
"no-underscore-dangle": ["error", { "allow": ["__blogPostData"] }]
}
}
Then I set the lint script :
"lint": "eslint src --fix",
It's listing correctly all my .js files , but I don't see any warnings/errors in my .ts files ( I doubt they are all well written...)
Am I wrong or missing anything in my eslint setup for typescript ?

parser is a root-level config item, not a field of parserOptions:
"eslintConfig": {
"parser": "typescript-eslint-parser"
"parserOptions": { ...options },
"plugins": ["typescript"]
}
Also, the parser and plugin you are using are deprecated. The newer/maintained projects are both available at https://github.com/typescript-eslint/typescript-eslint. (Config is the same, just with updated names). Here is an nice step-by-step walk-through on how to set this up - https://dev.to/robertcoopercode/using-eslint-and-prettier-in-a-typescript-project-53jb
Note that rather than defining your eslint config in package.json, you could instead use a separate.eslintrc.{js,yaml}. One in the root directory would setup your standard rules for JavaScript and another one in ./src/server could setup the TypeScript parser & plugin only for the relevant directory (but still pick up all your standard root rules).

You should use tslint for TypeScript, not eslint:
npm i tslint --save
after that, create a tslint.json in your project root (or pick one from the web with the rules you like). Just a link I found on Google: ts lint setup

Related

How to import d3.js in a node and typescript project? [ERR_REQUIRE_ESM]

I'm working on a node project using typescript, oclif and d3.js, among other things. Typescript was configured by npx when creating the project with oclif so I didn't control all aspects of it (especially regarding TS, and I'm not an expert. TS is great, but configuration wise, meh).
Anyway, everything was working fine, but I recently added d3 as a dependency and tried to build a document, and I get this error when running it:
(node:22554) [ERR_REQUIRE_ESM] Error Plugin: dbacl [ERR_REQUIRE_ESM]: require() of ES Module /dbacl/node_modules/d3/src/index.js from /dbacl/src/tree/graph-tree.ts not supported.
Instead change the require of index.js in /Users/nico/Furo/Dev/dbacl/src/tree/graph-tree.ts to a dynamic import() which is available in all CommonJS modules.
In the file where I'm using d3 I import it as per documentation:
import * as d3 from 'd3'
I suspect it might be a problem after compiling, so here is tsconfig.json. I didn't change anything since generation by npx.
{
"compilerOptions": {
"declaration": true,
"importHelpers": true,
"module": "commonjs",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"target": "es2019",
},
"include": [
"src/**/*"
]
}
And in case it's more relevant, here is my package.json file as well (didn't change anything either):
{
"name": "dbacl",
"version": "0.0.0",
"description": "",
"author": "",
"bin": {
"dbacl": "./bin/run"
},
"license": "MIT",
"main": "dist/index.js",
"repository": "*****/dbacl",
"files": [
"/bin",
"/dist",
"/npm-shrinkwrap.json",
"/oclif.manifest.json"
],
"dependencies": {
"#oclif/core": "^1",
"#oclif/plugin-help": "^5",
"#oclif/plugin-plugins": "^2.0.1",
"#types/d3": "^7.4.0",
"#types/jsdom": "^16.2.14",
"d3": "^7.6.1",
"directory-tree": "^3.3.0",
"jsdom": "^20.0.0",
"lodash": "^4.17.21"
},
"devDependencies": {
"#oclif/test": "^2",
"#types/chai": "^4",
"#types/mocha": "^9.0.0",
"#types/node": "^16.9.4",
"chai": "^4",
"eslint": "^7.32.0",
"eslint-config-oclif": "^4",
"eslint-config-oclif-typescript": "^1.0.2",
"globby": "^11",
"mocha": "^9",
"oclif": "^3",
"shx": "^0.3.3",
"ts-node": "^10.2.1",
"tslib": "^2.3.1",
"typescript": "^4.4.3"
},
"oclif": {
"bin": "dbacl",
"dirname": "dbacl",
"commands": "./dist/commands",
"plugins": [
"#oclif/plugin-help",
"#oclif/plugin-plugins"
],
"topicSeparator": " ",
"topics": {
"hello": {
"description": "Say hello to the world and others"
}
}
},
"scripts": {
"build": "shx rm -rf dist && tsc -b",
"lint": "eslint . --ext .ts --config .eslintrc",
"postpack": "shx rm -f oclif.manifest.json",
"posttest": "yarn lint",
"prepack": "yarn build && oclif manifest && oclif readme",
"test": "mocha --forbid-only \"test/**/*.test.ts\"",
"version": "oclif readme && git add README.md"
},
"engines": {
"node": ">=12.0.0"
},
"keywords": [
"oclif"
],
"types": "dist/index.d.ts"
}
I find this problem quite confusing because everywhere I've been searching about this problem, it seems I'm doing the right thing. I assume the problem might be between my screen and my chair, but really I don't get it. Also, should I use the dynamic import like this?
const d3 = await import('d3')
I tried, it didn't work. I made the function that generates the document async and added that line at the start but nope. Anyway, if I believe the error, that would be the way to go but I didn't see this solution anywhere when looking for a solution to my problem. What do you guys think?
Thanks
So thanks to the input from a colleague and this article, the problem is that d3 now supports ESM only. So when the compiler turns the import into
// index.ts
import * as d3 from 'd3'
// compiled index.js
const d3 = require('d3')
it just doesn't work. I was using d3 version 7, and a quick fix to it was to downgrade to version 6.7.0, when it did support commonJS.
Now, I have to move on with this project, but I'll keep looking into it and into how I can use a recent version of d3 in my project. If I do, I'll edit that answer!
Cheers

Import HTML as string and test with Jest

I'm using sveltekit and I can't use the files api to import html templates. So I decided to import by writing a module that imports the content of the document as a string (described here).
// src/global.d.ts
/// <reference types="#sveltejs/kit" />
declare module '*.html' {
const content: string
export default content
}
So far so good, but now I need to test the code and jest can't interpret the code.
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/home/developer/workspace/src/assets/html/confirm_email.html:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<!DOCTYPE html>
^
SyntaxError: Unexpected token '<'
I don't understand how jest understands the .d.ts files... How do I get to test the code?
Do you install #babel/plugin-transform-runtime"?
I share my config for jest/svelte-jester..
I have:
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"$lib": ["src/lib"],
"$lib/*": ["src/lib/*"]
}
},
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"],
}
svelte.config.js
import vercel from '#sveltejs/adapter-vercel'
/** #type {import('#sveltejs/kit').Config} */
const config = {
kit: {
adapter: vercel(),
vite: {
define: {
'process.env': process.env,
},
},
},
transform: {
"^.+\\.svelte$": ["svelte-jester", { "preprocess": true }]
}
};
export default config;
babel.config.json
{
"presets": [
["#babel/preset-env", { "modules": "auto" }]
],
"plugins": ["babel-plugin-transform-vite-meta-env","#babel/plugin-transform-runtime"]
}
jest.config.js
export default {
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.svelte$": "svelte-jester",
},
"moduleFileExtensions": ["svelte", "js"],
"testEnvironment": "jsdom",
"setupFilesAfterEnv": ["#testing-library/jest-dom/extend-expect"]
}
and whole package.json
{
"name": "sveltekit",
"version": "0.0.1",
"scripts": {
"dev": "svelte-kit dev",
"build": "svelte-kit build",
"package": "svelte-kit package",
"preview": "svelte-kit preview",
"test": "jest src",
"test:watch": "npm run test -- --watch"
},
"devDependencies": {
"#babel/core": "^7.16.12",
"#babel/plugin-transform-modules-commonjs": "^7.16.8",
"#babel/plugin-transform-runtime": "^7.17.0",
"#babel/preset-env": "^7.16.11",
"#supabase/supabase-js": "^1.29.1",
"#sveltejs/adapter-auto": "^1.0.0-next.7",
"#sveltejs/kit": "^1.0.0-next.215",
"#sveltejs/svelte-virtual-list": "^3.0.1",
"#testing-library/svelte": "^3.0.3",
"autoprefixer": "^10.4.1",
"babel-jest": "^27.4.6",
"babel-plugin-transform-vite-meta-env": "^1.0.3",
"jest": "^27.4.7",
"postcss-load-config": "^3.1.1",
"prettier": "^2.5.1",
"prettier-plugin-svelte": "^2.5.1",
"svelte": "^3.44.0",
"svelte-jester": "^2.1.5",
"svelte-lazy": "^1.0.12",
"tailwindcss": "^3.0.8",
"ts-jest": "^27.1.3"
},
"type": "module",
"dependencies": {
"#fontsource/fira-mono": "^4.5.0",
"#lukeed/uuid": "^2.0.0",
"#testing-library/jest-dom": "^5.16.1",
"cookie": "^0.4.1",
"svelte-lazy-image": "^0.2.0",
"swiper": "^8.0.3"
},
"testEnvironment": "jsdom"
}
I hope it will help you.I had a lot of troubles too with setting up jest..
1.Import html as string
I solved the problem using another approach...
I'm using a resource of vite to import the html file as an asset, as can be seen here in the documentation
import confirm_email_template from '../../../assets/html/confirm_email.html?raw'
2.Test using Jest
For production it works perfectly, but for unit testing the code breaks because Jest can't import the asset as a module.
So the second part of the problem was fixed (I don't know if this is the best practice) using asset mocks.
// jest.config.cjs
{
⋮
moduleNameMapper: {
⋮
'([a-zA-Z_ ]+\\.html)\\?raw$': '<rootDir>/__mocks/$1.cjs'
}
⋮
}
To make it work, I created the following folder structure:
__mocks
|
confirm_email.html.cjs
another_asset_mocked.html.cjs
The confirm_email.html.cjs looks like this:
// __mocks/confirm_email.html.cjs
module.exports = '<html>content<html>'

Eslint instalation "A config file was still generated, but the config file itself may not follow your linting rules" How to fix it?

I am instaling eslint into a new empty folder and I received this message:
An error occurred while generating your JavaScript config file. A config file was still generated, but the config file itself may not follow your linting rules.
I am following this steps:
npm init -y
npm i -D eslint
npx eslint --init
Error: An error occurred while generating your JavaScript config file. A config file was still generated, but the config file itself may not follow your linting rules.
Error: Cannot find module 'C:\Users\vgva\Desktop\Nueva carpeta\para-pruebas-git\node_modules\espree\dist\espree.cjs'
at createEsmNotFoundErr (node:internal/modules/cjs/loader:960:15)
at finalizeEsmResolution (node:internal/modules/cjs/loader:953:15)
at resolveExports (node:internal/modules/cjs/loader:482:14)
at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (C:\Users\vgva\Desktop\Nueva carpeta\para-pruebas-git\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
at Object.<anonymous> (C:\Users\bgva\Desktop\Nueva carpeta\para-pruebas-git\node_modules\eslint\lib\rules\utils\ast-utils.js:13:16)
at Module._compile (C:\Users\vgva\Desktop\Nueva carpeta\para-pruebas-git\node_modules\v8-compile-cache\v8-compile-cache.js:192:30)
File package.json:
{
"name": "para-pruebas-git",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"eslint": "^7.32.0",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.1.1",
"eslint-plugin-react": "^7.27.0"
}
}
File .eslintrc.js
module.exports = {
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": [
"plugin:react/recommended",
"standard"
],
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 13,
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
}
};
What is that error about and why? How to fix it?
I have faced the same problem. First I thought Spree might have broken the Semver principle, and I might need to somehow force an older version; but since that path was hacky IMO I decided to first try Yarn with the whole process, just to test my luck, and it worked!
remove node_modules dir
yarn
yarn eslint --init
and it just worked as expected.
Just make sure you have the correct node.js version.
Note that eslint only works with ^12.22.0, ^14.17.0, or >=16.0.0
After node.js is updated, run npm install again.

Using external babel configuration

I'm using #babel/node package in my project
and when I run my project as:
npm run dev
I'm getting this message in cmd window:
> Using external babel configuration
> Location: "...(project folder path)\.babelrc"
And when I build my project jsx files, I received errors .
How to solve it?
Dev dependencies:
"devDependencies": {
"#babel/node": "^7.7.4",
"#babel/preset-env": "^7.7.6",
"babel-preset-env": "^1.7.0",
"nodemon": "^1.19.4"
}
.babelrc file:
{
"presets": ["next/babel", "#babel/preset-env"]
}
Had the same issue, removed "#babel/preset-env" in .babelrc file. Deleting this part solves the issue (worked for me).
My babel.rc for developing js apps using nodejs is like this:
{
"presets": [
["#babel/preset-env"],
],
"plugins": [
["#babel/transform-runtime"]
],
"env": {
"development": {
"sourceMaps": true,
"retainLines": true
}
}
}
And my dev script is like this:
"dev": "./node_modules/.bin/cross-env NODE_ENV=development ./node_modules/.bin/nodemon --exec ./node_modules/.bin/babel-node src/index.js | pino-pretty",
I use cross-env and pino, you can remove it.
I hope helpful.

Eslint configuration is showing a `definition for rule 'filenames/match-regex' was not found` error

I'm getting started with Walmart's new React framework called Electrode.
I'm trying to configure eslint and have tried extending the walmart lint configuration like so:
https://github.com/walmartlabs/eslint-config-walmart
Here's the .eslintrc
{
"parser": "babel-eslint",
"ecmaFeatures": {
"jsx": true
},
"env": {
"es6": true
},
"extends": "walmart/configurations/es6-react-test",
"rules": {
"indent": ["error", 2]
}
}
and package.json
"devDependencies": {
"babel-eslint": "^7.1.1",
"electrode-archetype-react-app-dev": "^1.0.0",
"eslint": "^2.10.2",
"eslint-plugin-filenames": "^1.0.0",
"eslint-plugin-react": "^5.1.1",
"gulp": "^3.9.1"
},
but I get a definition for rule 'filenames/match-regex' was not found error. I installed eslint-plugin-filenames, was there something else I need to confgure as well?
file: 'file:///foo/client/components/home.jsx'
severity: 'Error'
message: 'Definition for rule 'filenames/match-regex' was not found (filenames/match-regex)'
at: '1,1'
source: 'eslint'
Try running ESLint from your node_modules instead of the one you have installed globally. Something like this:
node_modules/eslint/bin/eslint.js --fix .
Otherwise your ESLint plugins might not get picked up.
Try upgrading the packages, I don't see any such issues now with the new versions.
For configuring/overriding default eslint config refer the Electrode docs
For example to override default eslint config for client(react), I created a .eslintec file in client folder, with below snippet:
---
extends:
- "../../node_modules/electrode-archetype-react-app-dev/config/eslint/.eslintrc-react"
- "eslint:recommended"
parser:
"babel-eslint"
rules:
quotes:
- 2
- "single"

Resources