I have the following config for Jest, which I was expecting to transform modules foo and bar inside node_modules, but ignore the rest:
{
"transformIgnorePatterns": [
"node_modules/(?!(foo)/)",
"node_modules/(?!(bar)/)"
]
}
But it seems like neither are being transformed. Why?
The answer lies hidden in the documentation (emphasis mine):
If the file path matches any of the patterns, it will not be transformed.
The regex above creates a combination where any folder under node_modules will either match in the first pattern or the second pattern. Here's a visualization of the regex:
If the goal is to not match against certain libraries in node_modules, this combination of regex patterns make that impossible.
The solution is to combine them into a single statement:
{
"transformIgnorePatterns": [
"node_modules/(?!(foo|bar)/)"
]
}
Related
I don't know what happened, suddenly, all my applications that make use of glob paths broke.
Jasmine, TypeORM, any library I need to specify directories through of glob patterns don't work on my Windows.
I dove deeply into those libraries trying to solve the issue. I figured out that libraries use some path module's functions, like join and normalize, to handle the paths before passing them to the glob module. Let me show a code snippet from Jasmine library:
includeFiles.forEach(function(file) {
if(!(path.isAbsolute && path.isAbsolute(file))) {
file = path.join(jasmineRunner.projectBaseDir, jasmineRunner.specDir, file);
}
var filePaths = glob.sync(file, { ignore: excludeFiles });
C:\Users\User\Programmation\project\test***[sS]pec.js
The join function converts all slashes from path to backslashes, but the glob module doesn't recognize paths with backslashes. The same thing happens with TypeORM using the normalize function from the path module under the hood.
const allFiles = directories.reduce((allDirs, dir) => {
return allDirs.concat(glob_1.default.sync(PlatformTools_1.PlatformTools.pathNormalize(dir)));
}, []);
The curious thing is that everything has worked before. I don't know exactly when it stopped working, but it did.
I encountered a similar problem.
After digging inside the TypeORM code I realized the problem is with the glob library.
glob has a problem with the windows separator.
I ended up replacing the separator like this:
entities: [
(__dirname+"\\..\\entities\\**\\*.entity{.ts,.js}").replace(/\\/g,'/')
],
Original Question
How do I correctly "configure" the (unified, remark, remark-lint) remark-lint-no-undefined-references plugin/rule "allow" option for use with the remark-cli?
My goal is to configure the rule to ignore the Azure DevOps Wiki's non-standard table of contents tag, [[_TOC_]]. My simplified setup entails:
All packages globally installed. Probably not relevant.
A parent folder in which I have:
A package.json file.
A Test folder containing just the one Test.md file whose only content is this one line [[_TOC_]].
From a command prompt whose working folder is the aforementioned parent folder, I execute:
remark Test
Default Operation
The default operation, i.e. just the plugin/rule specified in the package.json file, returns the expected warning. This is, presumably, due to the non-standard tag, [[_TOC_]]. This is the warning I wish to turn off.
package.json (default)
{
"remarkConfig": {
"plugins": [
"remark-lint-no-undefined-references"
]
}
}
Execution and Expected Warning (default)
C:\..>remark Test
test\Test.md
1:1-1:10 warning Found reference to undefined definition no-undefined-references remark-lint
1:2-1:9 warning Found reference to undefined definition no-undefined-references remark-lint
‼ 2 warnings
What I've tried
I've tried to adapt remark-lint-no-undefined-references API example and Configuration, 'rules can be configured in one standard way' to my package.json file. After much trial and error, I've ended up with this seemingly valid json:
package.json
{
"remarkConfig": {
"plugins": [
"remark-lint-no-undefined-references", [1, {
"allow": ["[[_TOC_]]"]
}]
]
}
}
The Online JSON Viewer and JSONLint indicate it's valid JSON. However, remark-cli yields this error. Other variations yielded different errors. I am stumped.
C:\..>
Test\Test.md
1:1 error Error: Cannot parse file `package.json`
Expected preset, not `1`
at Error (file:///C:/Users/scott.welker/AppData/Roaming/npm/node_modules/remark-cli/node_modules/fault/index.js:39:12)
at file:///C:/Users/scott.welker/AppData/Roaming/npm/node_modules/remark-cli/node_modules/unified-engine/lib/find-up.js:190:15
at done (file:///C:/Users/scott.welker/AppData/Roaming/npm/node_modules/remark-cli/node_modules/trough/index.js:145:7)
× 1 error
Update 03/14/2022
I've made some progress thanks to a bit of help on GitHub Issue (#210). However, that was not the right avenue and it is closed. My issue remains.
A Few Things are Apparent
My initially inferred JSON, package.json, is incorrect. See Hacked my JSON below.
I failed to appreciate how the non-standard Azure DevOps Wiki table of contents tag, [[_TOC_]], is interpreted. See Tag Interpretation (console-log) following.
My inferred package.json seemingly remains incorrect. See My JSON Must Still be Wrong below.
Hacked my JSON
To overcome ...Error: Cannot parse file 'package.json', Expected preset, not '1' I hacked my file so that I now have the following. This change overcomes the error and enables me to continue but it is still seemingly incorrect. See My JSON Must Still be Wrong.
package.json file
{
"remarkConfig": {
"plugins": [
"remark-lint-no-undefined-references", {
"allow": ["_TOC_", "[_TOC_]"]
}
]
}
}
Tag Interpretation (console.log)
After hacking my JSON, I added a recommended console.log (..\npm\node_modules\remark-lint-no-undefined-references\index.js) of id. This reveals that the linting interprets the table of contents tag as two separate bits of concerning markdown, _TOC_ and [_TOC_]. I did not appreciate this. However, the findings below suggest this may not be a problem. See My JSON Must Still be Wrong.
remark-cli
C:\..>remark Test
Id: _TOC_
Id: [_TOC_]
Test\Test.md
1:1-1:10 warning Found reference to undefined definition no-undefined-references remark-lint
1:2-1:9 warning Found reference to undefined definition no-undefined-references remark-lint
‼ 2 warnings
My JSON Must Still be Wrong
Referring to another location in the source here (line 126), when I replace that const allow definition with this hard-coded declaration, const allow = new Set(["_TOC_", "[_TOC_]"]), I get the desired behavior. E.g.:
remark-cli
C:\...>remark Test
Test\Test.md: no issues found
Next Steps:
See whether I can forgo the package.json and instead use pure javascript. Either my JSON is incorrect or it isn't being interpreted correctly.
Continue to futz with the JSON. What I've inferred may well be wrong.
The following guess also fails to suppress the unwanted warnings:
package.json
{
"remarkConfig": {
"plugins": [
"remark-lint-no-undefined-references", [{
"allow": ["_TOC_", "[_TOC_]"]
}]
]
}
}
Update 03/28/2022
CAUTION!
While the setup in this update is valid, the Test.js example code is flawed. See 03/30/2022 Update below.
Following up on "Next Step, see whether I can forgo the package.json and instead use pure javascript."
I seem to have made it work except it suppresses all warnings, not just the few (two) that I am targeting. More development and testing is needed.
New Setup
A new parent Node.js application folder in which I have:
Opted to re-install all packages, and some new ones, but not globally (this time):
npm install to-vfile
npm install vfile-reporter
npm install remark
npm install remark-lint
npm install remark-lint-no-undefined-references
The node_modules folder. Created and populated by npm installs (dependencies).
A package.json file. Created and populated by npm installs.
A package-lock.json file. Created and populated by npm installs.
A copy of the same Test folder containing just the one Test.md file whose only content is this one line [[_TOC_]].
From a command prompt whose working folder is the aforementioned parent folder, I execute my new node/javascript code:
node Test.js See following. Code comments illustrate the unexpected suppression of all warnings, even those not targeted.
Test.js
WARNING! This code is incorrect. See the 03/30/2022 Update below.
import {reporter} from 'vfile-reporter'
import {remark} from 'remark'
import remarkLint from 'remark-lint'
import remarkLintNoUndefinedReferences from 'remark-lint-no-undefined-references'
import {read} from 'to-vfile'
main()
async function main() {
const file = await remark()
.use(remarkLint)
// This useage results in the expected warnings, '...Found reference to undefined definition...'
.use(remarkLintNoUndefinedReferences)
// This usage suppresses the warnings, as desired. However, note the next usage.
//.use(remarkLintNoUndefinedReferences[ { allow: [ '_TOC_', '[_TOC_]' ] }])
// This usage also suppresses the warning but it shoud not have done so.
//.use(remarkLintNoUndefinedReferences[ { allow: [ '...', '…' ] }])
// This usage (and related tests) seem to illustrate that anything in the allowed array suppresses all warnings.
//.use(remarkLintNoUndefinedReferences[ { allow: [ '' ] }])
.process(await read('.\\Test\\Test.md'))
console.error(reporter(file))
}
Update 03/30/2022
Here is a corrected Test.js file where my invalid usages are commented out, marked WRONG, and the two correct usages are marked GOOD. The final usage corrects mistakes made in my 03/28/2022 update. I now have a working javascript version. I just need to adapt this known working version to the remark-cli's package.json file. Getting very close.
I arrived at this CORRECT, working usage through trial and error. My trial and error was aided by adding console.log() statements to the ..\remark-lint-no-undefined-references\index.js source and tweaking my javascript code as guided by repeated re-reading of the remark-lint Configure section.
Test.js
import {reporter} from 'vfile-reporter'
import {remark} from 'remark'
import remarkLint from 'remark-lint'
import remarkLintNoUndefinedReferences from 'remark-lint-no-undefined-references'
import {read} from 'to-vfile'
main()
async function main() {
const file = await remark()
.use(remarkLint)
// WRONG: This usage seems to suppress the warnings, as desired. However, note the next usage.
//.use(remarkLintNoUndefinedReferences[ { allow: [ '_TOC_', '[_TOC_]' ] }])
// WRONG: This usage also seems to supresses the warnings but, it shoud not have done so.
//.use(remarkLintNoUndefinedReferences[ { allow: [ '...', '…' ] }])
// WRONG: This usage (and related tests) seem to illustrate that anything in the allowed array suppresses all warnings.
//.use(remarkLintNoUndefinedReferences[ { allow: [ '' ] }])
// GOOD: This usage results in the expected warnings, '...Found reference to undefined definition...'
//.use(remarkLintNoUndefinedReferences)
// GOOD: This usage seems to be correct!!
.use(remarkLintNoUndefinedReferences, [1, { allow: [ '_TOC_', '[_TOC_]' ] }])
.process(await read('.\\Test\\Test.md'))
console.error(reporter(file))
}
Execution and Output
C:\..>node Test.js
DEBUG remarkTest: allow contains 2 items.
DEBUG remarkTest Id: '_TOC_'
DEBUG remarkTest Id: '[_TOC_]'
.\Test\Test.md: no issues found
The package.json below correctly "configures" the remark-lint-no-undefined-references plugin/rule "allow" option for use with remark-cli.
Note: I also transitioned away from globally installed packages out of an unsubstantiated concern that they might have contributed to my problem. See Multiple globally installed presets and plugins don’t work #165. This transition accounts for the added package.json "dependencies". See following.
package.json
I arrived at this by working from my 03/30/2022 update and futzing with varying syntax illustrated in the Unified Engine, Configuration, Schema section.
Again, my goal is to configure the rule to ignore the Azure DevOps Wiki's non-standard table of contents tag, [[_TOC_]].
{
"remarkConfig": {
"plugins": {
"remark-lint-no-undefined-references": { "allow":[ "_TOC_", "[_TOC_]" ] }
}
},
"dependencies": {
"remark": "^14.0.2",
"remark-lint": "^9.1.1",
"remark-lint-no-undefined-references": "^4.1.1"
}
}
Execution and Output
Note: my debug console.log(...) remains in place.
C:\..>remark Test
DEBUG remarkCLITest: allow contains 2 items.
Test\Test.md: no issues found
Let's say that I have a project structure like below:
src/index.js
src/test/foo.js
test/integration/src/index.test.js
test/unit/src/index.test.js
jest.config.json
In jest.config.json I have my testMatch
{
"testMatch": [
"test/**"
]
}
When I run jest with --config jest.config.json it matches with 0 file.
testMatch: test/** - 0 matches
testPathIgnorePatterns: /node_modules/ - 5 matches
testRegex: - 0 matches
Pattern: - 0 matches
I thought it might be related with some incorrect rootDir since testMatch is relative to that. I run jest in debug mode to see my root and it seems it's correct. It shows my project directory. (where jest.config.json exists)
When I change my testMatch to **/test/** it can detect my tests in test/ directory but that's not what I want because then it also matches with src/test/ directory.
Why it cannot detect my tests in test/ directory? Is my glob pattern incorrect?
Why it cannot detect my tests in test/ directory? Is my glob pattern incorrect?
Jest's glob implementation has been going through some issues as of late. Under the hood Jest uses micromatch, but why it is getting hung up on relative path globs is unclear.
There are a couple things you can try in your Jest config:
Include the <rootDir> string token directly in your testMatch glob like testMatch: ['<rootDir>/test/**'].
Follow the globstar example more closely from the Jest testMatch documentation, paying attention to the note about glob order:
Note: Each glob pattern is applied in the order they are specified in the config. (For example ["!/fixtures/", "/tests//.js"] will not exclude fixtures because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after /tests//.js.)
testMatch: [
'**/test/**',
'!**/src/**'
]
Is it possible to exclude/ignore a file when using Husky/lint-staged hooks?
Looking through the docs atm but not having any luck finding anything on this.
Was hoping there was something like an
/*ignore*/
tag that I could add.
To make lint-staged ignore certain files that were causing formatting issues.
Any thought on this greatly appreciated :)
Ended up adding
.prettierignore
file.
Not ideal but seems to do the job ok.
I finally found out how to do this (at least as of lint-staged v11.1.2)
In package.json:
"lint-staged": {
"!(path/to/excluded/dir/**/*)*.ts": [
"eslint --fix",
"prettier --write"
]
}
Note the globstar pattern is within the negation pattern and not outside it. This ensures that subdirectories are also excluded.
While configuring lint-staged in package.json or If you're using any other IDE, in order to ignore/exclude files by lint-Staged and husky hooks, you can add an "ignore" key in the lint-staged object to make it ignore whatever packages or files you want to ignore. Use the following extensible syntax:
{
"lint-staged": {
"linters": {
"src/**/*.js": ["formatter --write", "git add"],
},
"ignore": ["node_modules", "dist", "package-lock.json"] }
}
Just add the target pattern to 'linters' object and all the ignored files which you might be adding previously to .prettierignore to "ignore" key of lint-Staged object. And there you go!
If anyone still looking, take a look at this https://github.com/okonet/lint-staged#filtering-files It has good examples.
Filtering files
Linter commands work on a subset of all staged files, defined by a glob pattern. `lint-staged´ uses micromatch for matching files with the following rules:
If the glob pattern contains no slashes (/), micromatch's matchBase option will enabled, so globs match a file's basename regardless of directory:
"*.js" will match all JS files, like /test.js and /foo/bar/test.js
"!(*test).js". will match all JS files, except those ending in test.js, so foo.js but not foo.test.js
If the glob pattern does contain a slash (/), it will match for paths as well:
"./*.js" will match all JS files in the git repo root, so /test.js but not /foo/bar/test.js
"foo/**/\*.js" will match all JS files inside the/foodirectory, so/foo/bar/test.jsbut not/test.js
So I've been trying to find an answer for this for an entire day and looking at all the forums suggested that they use minimatch for glob check which might have been correct for older versions but they use micromatch for new version and to solve this issue we can use their pattern to exclude certain directories
So in your .lintstagedrc you can add the following pattern to avoid certain folders
{
"*.{json,md,html,scss}": ["prettier --write", "git add"],
["**/!(folder1|folder2)/*.ts"]: ["tslint --project tsconfig.json -c tslint.commit.json --fix", "prettier --write", "git add"]
}
So the glob here is an actual array and make sure not to pass this array within a string else it won't recognize the patterns also do not include **/*.ts the reason being lint-staged automatically converts this into a matchBase comparision if it finds / in the pattern so including this will also match against your folder1|folder2 files.
can fix in three ways:
.lintstagedrc.js
.prettierignore
lint-staged.config.js
more info : https://github.com/okonet/lint-staged/issues/797
Is it possible with ESLint to ignore one specific rule for an entire directory?
In my case, I would like to ignore import/prefer-default-export for a directory named commonComponents
ESLint configuration (.eslintrc) files are hierarchical:
ESLint will automatically look for them in the directory of the file to be linted, and in successive parent directories all the way up to the root directory of the filesystem. This option is useful when you want different configurations for different parts of a project or when you want others to be able to use ESLint directly without needing to remember to pass in the configuration file.
You can disable the import/prefer-default-export rule for the commonComponents directory by creating a .eslintrc file with the following content in that directory:
{
"rules": {
"import/prefer-default-export": "off"
}
}
You can also use the "overrides" key to declare rules for different glob patterns.
Have a read of Configuration Based on Glob Patterns
Sometimes a more fine-controlled configuration is necessary, for example if the configuration for files within the same directory has to be different. Therefore you can provide configurations under the overrides key that will only apply to files that match specific glob patterns, using the same format you would pass on the command line (e.g., app/**/*.test.js).
I use this to remove the no-unused-expressions rule from my test files like so;
"overrides": [{
"files": [ "*.spec.js" ],
"rules": {
"no-unused-expressions": 0
}
}]
If there are multiple directories that you want to apply your rules to, then you can create different configs for different purposes. For example:
.eslintrc.json for common config
.eslintrc-main.json for main linting and run eslint -c .eslintrc-main src test
.eslintrc-comp.json for components and run eslint -c .eslintrc-comp commonComponents fooBarComponent
YAML version :
rules:
no-unused-expressions: true
overrides:
- files: *-tests.js
rules:
no-unused-expressions: false
cretae .eslintignore file and put inside it your exluded folders. example :
node_modules/
functions/
dist/