### Run JSLint on a File Source: https://github.com/jslint-org/jslint/blob/beta/README.md Execute the downloaded jslint.mjs script on a JavaScript file from the shell. This example first creates a simple hello.js file. ```shell #!/bin/sh printf "console.log('hello world');\n" > hello.js node jslint.mjs hello.js ``` -------------------------------- ### Create V8 Coverage Report Programmatically in JavaScript Source: https://github.com/jslint-org/jslint/blob/beta/README.md This Node.js script uses JSLint's API to generate a V8 coverage report. It requires cloning a repository and installing its dependencies before execution. ```shell #!/bin/sh git clone https://github.com/tryghost/node-sqlite3 node-sqlite3-js \ --branch=v5.0.11 \ --depth=1 \ --single-branch cd node-sqlite3-js npm install node --input-type=module --eval ' /*jslint node*/ import jslint from "../jslint.mjs"; (async function () { // Create V8 coverage report from program `npm run test` in javascript. await jslint.v8CoverageReportCreate({ coverageDir: "../.artifact/coverage_sqlite3_js/", processArgv: [ "--exclude=tes?//", "--exclude=tes[!0-9A-Z_a-z-]/", "--exclude=tes[0-9A-Z_a-z-]/", "--exclude=tes[^0-9A-Z_a-z-]/", "--exclude=test/**/*.js", "--exclude=test/suppor*/*elper.js", "--exclude=test/suppor?/?elper.js", "--exclude=test/support/helper.js", "--include=**/*.cjs", "--include=**/*.js", "--include=**/*.mjs", "--include=li*/*.js", "--include=li?/*.js", "--include=lib/", "--include=lib/**/*.js", "--include=lib/*.js", "--include=lib/sqlite3.js", "npm", "run", "test" ] }); }()); ' ``` -------------------------------- ### Set Default Source Code for Editor Source: https://github.com/jslint-org/jslint/blob/beta/index.html Sets the default source code for the CodeMirror editor if not in debug mode. Includes example JSLint directives and a basic 'hello world' evaluation. ```javascript if (!mode_debug) { editor.setValue(String( `#!/usr/bin/env node /*jslint browser, node*/ /*global caches, indexedDb*/ import https from "https"; import jslint from \u0022./jslint.mjs\u0022; /*jslint-disable*/ JSLint will ignore and treat this region as blank-lines. Syntax error.\u0020\u0020\u0020\u0020 /*jslint-enable*/ eval("console.log(\\\"hello world\\\"');"); //jslint-ignore-line eval("console.log(\\\"hello world\\\"');"); // Optional directives. // .... /*jslint beta*/ .......... Enable experimental warnings. // .... /*jslint bitwise*/ ....... Allow bitwise operator. // .... /*jslint browser*/ ....... Assume browser environment. // .... /*jslint convert*/ ....... Allow conversion operator. // .... /*jslint couch*/ ......... Assume CouchDb environment. // .... /*jslint devel*/ ......... Allow console.log() and friends. // .... /*jslint eval*/ .......... Allow eval(). // .... /*jslint fart*/ .......... Allow complex fat-arrow. // .... /*jslint for*/ ........... Allow for-statement. // .... /*jslint getset*/ ........ Allow get() and set(). // .... /*jslint indent2*/ ....... Use 2-space indent. // .... /*jslint long*/ .......... Allow long lines. // .... /*jslint node*/ .......... Assume Node.js environment. // .... /*jslint nomen*/ ......... Allow weird property name. // .... /*jslint single*/ ........ Allow single-quote strings. // .... /*jslint subscript*/ ..... Allow identifier in subscript-notation. // .... /*jslint this*/ .......... Allow 'this'. // .... /*jslint trace*/ ......... Include jslint stack-trace in warnings. // .... /*jslint unordered*/ ..... Allow unordered cases, params, properties, // ................................... variables, and exports. // .... /*jslint white*/ ......... Allow messy whitespace. await (async function () { let result = await new Promise(function (resolve) { https.request("https://www.jslint.com/jslint.mjs", function (res) { result = ""; res.on("data", function (chunk) { result += chunk; }).on("end", function () { resolve(result); }).setEncoding("utf8"); }).end(); }); result = jslint.jslint(result); result.warnings.forEach(function ({ formatted_message }) { console.error(formatted_message); }); }()); `).trim() + "\n"); } ``` -------------------------------- ### Allow Weird Property Names with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint nomen*/` directive to allow property names that are not standard identifiers, such as those starting with an underscore. ```javascript /*jslint nomen*/ // Allow weird property name. let foo = {}; foo._bar = 1; ``` -------------------------------- ### Initialize Event Handling for Window Load Source: https://github.com/jslint-org/jslint/blob/beta/index.html Sets up event listeners and initializations when the window loads, including resizing UI elements and restoring JSLint options from localStorage. ```javascript window.addEventListener("load", function () { let state; // Resize ui-elements. listener_window_onresize(); // PR-391 - Initialize jslint-options from localStorage. try { state = JSON.parse(localStorage.getItem("jslint_persist_options")); } catch (ignore) {} state = state || {}; document.querySelectorAll( "#JSLINT_OPTIONS input[type=checkbox]" ).forEach(function (elem) { if (sta ``` -------------------------------- ### Initialize Event Handling for Hotkeys Source: https://github.com/jslint-org/jslint/blob/beta/index.html Sets up a global keydown event listener to trigger JSLint execution when Ctrl+Enter or Meta+Enter is pressed. ```javascript document.addEventListener("keydown", function (evt) { switch ((evt.ctrlKey || evt.metaKey) && evt.key) { case "Enter": case "e": evt.preventDefault(); evt.stopPropagation(); jslint_run(); break; } }); ``` -------------------------------- ### Call JSLint Function Source: https://github.com/jslint-org/jslint/wiki/JSLINT-in-a-web-page Demonstrates the basic syntax for calling the JSLint function with source code, optional configuration, and allowed global variables. ```javascript jslint(source, options, globals); ``` -------------------------------- ### Download JSLint CLI Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use curl to download the JSLint CLI script to your local machine. ```shell #!/bin/sh curl -L https://www.jslint.com/jslint.mjs > jslint.mjs ``` -------------------------------- ### Initialize CodeMirror with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/jslint_wrapper_codemirror.html Initializes a CodeMirror editor with JSLint integration enabled. Configure linting options and event handlers for before and after linting. ```javascript window.addEventListener("load", function () { let editor = window.CodeMirror.fromTextArea(document.getElementById( "editor1" ), { gutters: [ "CodeMirror-lint-markers" ], indentUnit: 4, lineNumbers: true, lint: { lintOnChange: true, // Enable auto-lint. options: { // browser: true, // node: true, // globals: [ // "caches", // "indexedDb" // ] } }, mode: "javascript" }); // Initialize event-handling before linter is run. editor.on("lintJslintBefore", function (/\* options \*/) { // options.browser = true; // options.node = true; // options.globals = [ // "caches", // "indexedDb" // ]; return; }); // Initialize event-handling after linter is run. editor.on("lintJslintAfter", function (options) { // Generate jslint-report from options.result. document.querySelector( ".JSLINT\_.JSLINT\_REPORT_" ).innerHTML = window.jslint.jslint_report(options.result); }); // Manually trigger linter. editor.performLint(); }); ``` -------------------------------- ### Initialize Event Handling for Buttons Source: https://github.com/jslint-org/jslint/blob/beta/index.html Sets up click event listeners for buttons within the #JSLINT_BUTTONS container to trigger actions like running JSLint, clearing options, or clearing the source code. ```javascript document.querySelector( "#JSLINT_BUTTONS" ).addEventListener("click", function ({ target }) { switch (target.name) { case "JSLint": jslint_run(); break; case "clear_options": document.querySelectorAll( "#JSLINT_OPTIONS input[type=checkbox]" ).forEach(function (elem) { elem.checked = false; }); document.querySelector("#JSLINT_OPTIONS").click(); document.querySelector("#JSLINT_GLOBALS").value = ""; persist_state(); break; case "clear_source": editor.setValue(""); editor.focus(); break; } }); ``` -------------------------------- ### Integrate JSLint with CodeMirror Source: https://github.com/jslint-org/jslint/blob/beta/README.md This HTML file demonstrates how to integrate JSLint with CodeMirror for real-time code linting. It includes necessary CSS and JavaScript assets for both libraries and sets up an editor with linting enabled. ```html CodeMirror: JSLint Demo

CodeMirror: JSLint Demo

This demo will auto-lint the code below, and auto-generate a report as you type.

``` -------------------------------- ### Enable Debug Mode and Click Trace Option Source: https://github.com/jslint-org/jslint/blob/beta/index.html Enables debug mode based on the URL query string and programmatically clicks the 'trace' input element if debug mode is active. ```javascript mode_debug = ( /\bdebug=1\b/ ).test(location.search); if (mode_debug) { document.querySelector( "#JSLINT_OPTIONS input[value=trace]" ).click(); } ``` -------------------------------- ### Initialize Window Resize Event Listener Source: https://github.com/jslint-org/jslint/blob/beta/index.html Adds an event listener to the window for the 'resize' event, triggering a specific handler function. ```javascript window.addEventListener("resize", listener_window_onresize); ``` -------------------------------- ### Generate V8 Coverage Report from Shell Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use this command in the shell to generate a V8 coverage report. It allows for detailed configuration of file inclusions and exclusions. ```shell node ../jslint.mjs \ v8_coverage_report=../.artifact/coverage_sqlite3_sh/ \ --exclude=tes?/ \ --exclude=tes[!0-9A-Z_a-z-]/ \ --exclude=tes[0-9A-Z_a-z-]/ \ --exclude=tes[^0-9A-Z_a-z-]/ \ --exclude=test/**/*.js \ --exclude=test/suppor*/*elper.js \ --exclude=test/suppor?/?elper.js \ --exclude=test/support/helper.js \ --include=**/*.cjs \ --include=**/*.js \ --include=**/*.mjs \ --include=li*/*.js \ --include=li?/*.js \ --include=lib/ \ --include=lib/**/*.js \ --include=lib/*.js \ --include=lib/sqlite3.js \ npm run test ``` -------------------------------- ### Initialize Event Handling for Globals Input Source: https://github.com/jslint-org/jslint/blob/beta/index.html Attaches a keyup event listener to the globals input field to trigger state persistence as the user types. ```javascript document.querySelector( "#JSLINT_GLOBALS" ).addEventListener("keyup", persist_state); ``` -------------------------------- ### Initialize Event Handling for Report Links Source: https://github.com/jslint-org/jslint/blob/beta/index.html Adds a click event listener to the report area to handle clicks on address elements, allowing users to jump to specific code locations. ```javascript document.querySelector( ".JSLINT_" ).addEventListener("click", function ({ target }) { switch (target.tagName) { // PR-368 - Website // Add clickable-links to editor-code in report-warnings and report-functions. case "ADDRESS": editor.focus(); editor.setCursor({ ch: Number(target.textContent.split(":")[1] - 1), line: Number(target.textContent.split(":")[0] - 1) }); break; } }); ``` -------------------------------- ### Create Pull Request for Code Changes Source: https://github.com/jslint-org/jslint/blob/beta/README.md Follow these steps to create a pull request for code changes, including verifying CI success and merging the changes. ```shell shGitPullrequest beta beta - verify ci-success for origin-branch-alpha - https://github.com/kaizhu256/jslint/actions ``` ```shell git push upstream alpha -f - verify ci-success for upstream-branch-alpha - https://github.com/jslint-org/jslint/actions ``` ```shell shGitPullrequestCleanup - verify ci-success for origin-branch-alpha - https://github.com/kaizhu256/jslint/actions ``` ```shell git push upstream alpha -f - verify ci-success for upstream-branch-alpha - https://github.com/jslint-org/jslint/actions ``` -------------------------------- ### JSLint Entire Directory in Shell Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use JSLint from the command line to lint all files within the current directory. This is a convenient way to check code quality across a project. ```shell #!/bin/sh # JSLint directory '.' node jslint.mjs . ``` -------------------------------- ### Run JSLint and Display Reports Source: https://github.com/jslint-org/jslint/blob/beta/index.html Executes the JSLint linter with specified options and displays the generated reports. Includes UI updates for loading and error handling. ```javascript function jslint_run() { document.querySelector("#uiLoader1 > div").textContent = "Linting"; document.querySelector("#uiLoader1").style.display = "flex"; try { // Wait awhile before running cpu-intensive linter so ui-loader doesn't jank. await new Promise(function (resolve) { setTimeout(resolve); }); // Update jslint_option_dict from ui-inputs. document.querySelectorAll( "#JSLINT_OPTIONS input[type=checkbox]" ).forEach(function (elem) { jslint_option_dict[elem.value] = elem.checked; }); jslint_option_dict.globals = document.querySelector( "#JSLINT_GLOBALS" ).value.trim().split( /[\s,;']+/ ); // Execute linter. editor.performLint(); // Generate the reports. // Display the reports. document.querySelector( ".JSLINT_REPORT_" ).innerHTML = jslint.jslint_report(jslint_option_dict.result); listener_window_onresize(); } catch (err) { console.error(err); //jslint-ignore-line } // Hide ui-loader-animation. setTimeout(function () { document.querySelector("#uiLoader1").style.display = "none"; }, 500); } ``` -------------------------------- ### Initialize CodeMirror Editor Source: https://github.com/jslint-org/jslint/blob/beta/index.html Initializes a CodeMirror editor instance for a textarea element, configuring various options like indentation, line numbers, and linting. ```javascript editor = CodeMirror.fromTextArea(document.querySelector( "#JSLINT_SOURCE textarea" ), { extraKeys: { "Shift-Tab": "indentLess", Tab: function () { if (editor.somethingSelected()) { editor.indentSelection("add"); return; } editor.replaceSelection(" "); } }, gutters: ["CodeMirror-lint-markers"], indentUnit: 4, lineNumbers: true, lineWrapping: true, lint: { lintOnChange: false, options: jslint_option_dict }, matchBrackets: true, mode: "javascript", showTrailingSpace: true, styleActiveLine: true }); ``` -------------------------------- ### Assume CouchDB Environment with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint couch*/` directive to assume a CouchDB environment, enabling specific checks relevant to CouchDB development. ```javascript /*jslint couch*/ // Assume CouchDb environment. registerType("text-json", "text/json"); ``` -------------------------------- ### Create JSLint Report from File in Shell Source: https://github.com/jslint-org/jslint/blob/beta/README.md Generate an HTML JSLint report from a specified JavaScript file using the command line. The report is saved to a designated HTML file. ```shell #!/bin/sh printf "function foo() {console.log('hello world');}\n" > hello.js # Create JSLint report from file 'hello.js' in shell. node jslint.mjs \ jslint_report=.artifact/jslint_report_hello.html \ hello.js ``` -------------------------------- ### Enable Experimental Warnings with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint beta*/` directive to enable experimental warnings and enforce specific coding standards like variable declaration order and case ordering in switch statements. ```javascript /*jslint beta*/ // Enable experimental warnings. // Warn if global variables are redefined. // Warn if const / let statements are not declared at top of function or // script, similar to var statements. // Warn if const / let / var statements are not declared in ascii-order. // Warn if named-functions are not declared in ascii-order. // Warn if cases in switch-statements are not in ascii-order. ``` -------------------------------- ### Import JSLint in CommonJS Environment Source: https://github.com/jslint-org/jslint/blob/beta/README.md Import JSLint in a CommonJS environment using dynamic import. This method is compatible with Node.js environments that use the CommonJS module system. ```shell #!/bin/sh node --eval ' /*jslint devel*/ (async function () { let globals = ["caches", "indexedDb"]; let jslint; let options = {browser: true}; let result; let source = "console.log(\'hello world\');\n"; // Import JSLint in CommonJS environment. jslint = await import("./jslint.mjs"); jslint = jslint.default; // JSLint and print . result = jslint.jslint(source, options, globals); result.warnings.forEach(function ({ formatted_message }) { console.error(formatted_message); }); }()); ' ``` -------------------------------- ### Assume Node.js Environment with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint node*/` directive to assume a Node.js environment, enabling Node.js-specific checks. ```javascript /*jslint node*/ // Assume Node.js environment. require("fs"); ``` -------------------------------- ### Commit Branch to Master Source: https://github.com/jslint-org/jslint/blob/beta/README.md Instructions for committing changes to the master branch, including updating CI configurations and verifying build success. ```shell shGitPullrequest master beta # re-run until version propagates - verify ci-success for origin-branch-alpha - https://github.com/kaizhu256/jslint/actions ``` ```shell git push upstream alpha -f - verify ci-success for upstream-branch-alpha - https://github.com/jslint-org/jslint/actions ``` ```shell shGitPullrequestCleanup - verify ci-success for origin-branch-alpha - https://github.com/kaizhu256/jslint/actions ``` ```shell git push upstream alpha -f - verify ci-success for upstream-branch-alpha - https://github.com/jslint-org/jslint/actions ``` ```shell git push origin beta:master - verify ci-success for origin-branch-master - https://github.com/kaizhu256/jslint/actions ``` ```shell git push upstream beta:master - verify ci-success for upstream-branch-master - https://github.com/jslint-org/jslint/actions ``` -------------------------------- ### Allow Console Logging with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint devel*/` directive to allow the use of `console.log()` and other development-related functions. ```javascript /*jslint devel*/ // Allow console.log() and friends. console.log("hello"); ``` -------------------------------- ### Initialize Event Handling for Options Panel Source: https://github.com/jslint-org/jslint/blob/beta/index.html Handles clicks within the options panel to toggle checkboxes and persist the state. Prevents default behavior if a checkbox is not directly clicked. ```javascript document.querySelector( "#JSLINT_OPTIONS" ).addEventListener("click", function (evt) { let elem = evt.target.closest( "#JSLINT_OPTIONS div[title]" ); elem = elem && elem.querySelector("input[type=checkbox]"); if (elem) { if (elem !== evt.target) { evt.preventDefault(); evt.stopPropagation(); elem.checked = !elem.checked; } persist_state(); } }); ``` -------------------------------- ### Initialize JSLint Source from Session Storage Source: https://github.com/jslint-org/jslint/blob/beta/index.html Initializes the JSLint source code from sessionStorage if debug mode is enabled. This helps in restoring previously entered code. ```javascript if (mode_debug) { try { editor.setValue(sessionStorage.getItem("jslint_persist_source")); } catch (ignore) {} } ``` -------------------------------- ### Create JSLint Report from Source in JavaScript Source: https://github.com/jslint-org/jslint/blob/beta/README.md Generate an HTML JSLint report programmatically within a JavaScript environment. This allows for dynamic report creation and integration into build processes. ```shell #!/bin/sh node --input-type=module --eval ' /*jslint devel*/ import jslint from "./jslint.mjs"; import fs from "fs"; (async function () { let result; let source = "function foo() {console.log(\'hello world\');}\n"; // Create JSLint report from in javascript. result = jslint.jslint(source); result = jslint.jslint_report(result); result = ` ${result}\n`; await fs.promises.mkdir(".artifact/", {recursive: true}); await fs.promises.writeFile(".artifact/jslint_report_hello.html", result); console.error("wrote file .artifact/jslint_report_hello.html"); }()); ' ``` -------------------------------- ### JSLint Browser Companion Script Source: https://github.com/jslint-org/jslint/blob/beta/index.html This script is the web companion file for JSLint, handling browser interactions and displaying reports. It requires the CodeMirror and JSLint libraries to be loaded. ```javascript // browser.mjs // The Unlicense // // This is free and unencumbered software released into the public domain. // // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non-commercial, and by any // means. // // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /*jslint beta, browser*/ /*property CodeMirror, Tab, addEventListener, ch, checked, clear, click, closest, ctrlKey, display, dom_style_report_unmatched, editor, error, extraKeys, focus, forEach, from, fromTextArea, getItem, getValue, globals, gutters, indentSelection, indentUnit, innerHTML, jslint, jslint_edition, jslint_report, key, length, line, lineNumbers, lineWrapping, lint, lintOnChange, matchBrackets, metaKey, mode, name, offsetWidth, on, options, parse, performLint, preventDefault, push, querySelector, querySelectorAll, replace, replaceSelection, result, reverse, search, setCursor, setItem, setSize, setValue, showTrailingSpace, somethingSelected, sort, split, stopPropagation, stringify, style, styleActiveLine, tagName, target, test, textContent, trim, value, width */ // This is the web script companion file for JSLint. It includes code for // interacting with the browser and displaying the reports. let CodeMirror = window.CodeMirror; let editor; let jslint = window.jslint; let jslint_option_dict = {}; let mode_debug; let mode_persist_state_debouncing; ``` -------------------------------- ### Persist UI State to Local and Session Storage Source: https://github.com/jslint-org/jslint/blob/beta/index.html Saves JSLint options, globals, and source code to localStorage and sessionStorage to maintain user preferences across sessions. Uses debouncing for performance. ```javascript function persist_state(mode) { // PR-391 - Persist ui-state to localStorage and sessionStorage. let state; // Debounce this function. if (mode !== "mode_debounced") { if (!mode_persist_state_debouncing) { mode_persist_state_debouncing = true; setTimeout(persist_state, 100, "mode_debounced"); } return; } mode_persist_state_debouncing = undefined; // Persist jslint-options to localStorage. state = {}; document.querySelectorAll( "#JSLINT_OPTIONS input[type=checkbox]" ).forEach(function (elem) { state[elem.value] = elem.checked; }); try { localStorage.setItem("jslint_persist_options", JSON.stringify(state)); } catch (ignore) { localStorage.clear(); localStorage.setItem("jslint_persist_options", JSON.stringify(state)); } // Persist jslint-globals to sessionStorage. if (mode_debug) { state = document.querySelector("#JSLINT_GLOBALS").value; if (state.length <= 0x10000) { try { sessionStorage.setItem("jslint_persist_globals", state); } catch (ignore) { sessionStorage.clear(); sessionStorage.setItem("jslint_persist_globals", state); } } } // Persist jslint-source to sessionStorage. if (mode_debug) { state = editor.getValue(); if (state.length <= 0x10000) { try { sessionStorage.setItem("jslint_persist_source", state); } catch (ignore) { sessionStorage.clear(); sessionStorage.setItem("jslint_persist_source", state); } } } } ``` -------------------------------- ### Assume Browser Environment with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint browser*/` directive to inform JSLint that the code is intended for a browser environment, enabling browser-specific checks. ```javascript /*jslint browser*/ // Assume browser environment. localStorage.getItem("foo"); ``` -------------------------------- ### Initialize JSLint Globals from Session Storage Source: https://github.com/jslint-org/jslint/blob/beta/index.html Initializes the JSLint globals from sessionStorage if debug mode is enabled. This allows for persistent global settings across sessions. ```javascript if (mode_debug) { try { document.querySelector( "#JSLINT_GLOBALS" ).value = sessionStorage.getItem("jslint_persist_globals"); } catch (ignore) {} } ``` -------------------------------- ### Import JSLint in ES Module Environment Source: https://github.com/jslint-org/jslint/blob/beta/README.md Import JSLint using an ES Module import statement. This is suitable for modern JavaScript environments that support ES Modules. ```shell #!/bin/sh node --input-type=module --eval ' /*jslint devel*/ // Import JSLint in ES Module environment. import jslint from "./jslint.mjs"; let globals = ["caches", "indexedDb"]; let options = {browser: true}; let result; let source = "console.log(\'hello world\');\n"; // JSLint and print . result = jslint.jslint(source, options, globals); result.warnings.forEach(function ({ formatted_message }) { console.error(formatted_message); }); ' ``` -------------------------------- ### Include Stack Trace in Warnings with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint trace*/` directive to include detailed stack traces in JSLint warnings, aiding in debugging. ```javascript /*jslint trace*/ // Include jslint stack-trace in warnings. console.log('hello world'); /* 1. Undeclared 'console'. console.log('hello world'); Error at warn_at (...) at warn (...) at lookup (...) at pre_v (...) at jslint.mjs 2. Use double quotes, not single quotes. console.log(...); Error at warn_at (...) at lex_string (...) at lex_token (...) at jslint_phase2_lex (...) at Function.jslint (...) at jslint.mjs */ ``` -------------------------------- ### Allow Getters and Setters with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint getset*/` directive, along with `this` and `devel`, to allow the use of getter and setter methods in JavaScript objects. ```javascript /*jslint getset, this, devel*/ // Allow get() and set(). let foo = { bar: 0, get getBar() { return this.bar; }, set setBar(value) { this.bar = value; } }; console.log(foo.getBar); // 0 foo.setBar = 1; console.log(foo.getBar); // 1 ``` -------------------------------- ### Run JSLint in Browser Source: https://github.com/jslint-org/jslint/blob/beta/index.html This asynchronous function is designed to run JSLint within a browser environment and generate HTML reports. It includes logic to display a UI loader animation. ```javascript async function jslint_run() { // This function will run jslint in browser and create html-reports. // Show ui-loader-animation. document.querySele ``` -------------------------------- ### Allow For-Loops with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint for*/` directive to allow the use of traditional `for` loops in your JavaScript code. ```javascript /*jslint for*/ // Allow for-loop. function foo() { let ii; for (ii = 0; ii < 10; ii += 1) { foo(); } } ``` -------------------------------- ### Configure JSLint to Allow Messy Whitespace Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the 'white' directive to instruct JSLint to ignore whitespace variations. ```javascript /*jslint white*/ // Allow messy whitespace. let foo = 1; let bar = 2; ``` -------------------------------- ### Export DOM Style Report and Editor Source: https://github.com/jslint-org/jslint/blob/beta/index.html Exports the 'dom_style_report_unmatched' function and the 'editor' instance to the global window object for external access. ```javascript window.dom_style_report_unmatched = dom_style_report_unmatched; window.editor = editor; ``` -------------------------------- ### Adjust UI Elements on Window Resize Source: https://github.com/jslint-org/jslint/blob/beta/index.html Resizes UI elements, particularly the editor, to fit the current browser dimensions to ensure proper layout and functionality. ```javascript function listener_window_onresize() { // This function will properly size ui-elements given current browser // dimensions. let content_width = document.querySelector( "#JSLINT_OPTIONS" ).offsetWidth; // Set explicit content-width for overflow to work properly. document.querySelectorAll( ".JSLINT_ fieldset > div" ).forEach(function (elem) { if (!elem.closest("#JSLINT_OPTIONS")) { elem.style.width = content_width + "px"; } }); editor.setSize(content_width); } ``` -------------------------------- ### Allow Bitwise Operators with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint bitwise*/` directive to allow the use of bitwise operators in your JavaScript code. ```javascript /*jslint bitwise*/ // Allow bitwise operator. let foo = 0 | 1; ``` -------------------------------- ### Use 2-Space Indent with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint indent2*/` directive to enforce a 2-space indentation style in your JavaScript code. ```javascript /*jslint indent2*/ // Use 2-space indent. function foo() { return; } ``` -------------------------------- ### Set JSLint Edition Text Source: https://github.com/jslint-org/jslint/blob/beta/index.html Updates the text content of an element to display the current JSLint edition. ```javascript document.querySelector("#JSLINT_EDITION").textContent = ( "Edition: " + jslint.jslint_edition ); ``` -------------------------------- ### Allow Single-Quote Strings with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint single*/` directive to allow the use of single quotes for string literals. ```javascript /*jslint single*/ // Allow single-quote strings. let foo = ''; ``` -------------------------------- ### Persist Editor State on Change Source: https://github.com/jslint-org/jslint/blob/beta/index.html Attaches an event listener to the CodeMirror editor to call the 'persist_state' function whenever the editor content changes. ```javascript editor.on("change", persist_state); ``` -------------------------------- ### Allow Subscript Notation with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint subscript*/` directive to allow the use of bracket notation for accessing object properties, even when a direct identifier is possible. ```javascript /*jslint subscript*/ // Allow identifiers in subscript-notation. let foo = {}; foo["bar"] = 1; ``` -------------------------------- ### Allow Conversion Operators with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint convert*/` directive to allow the use of conversion operators, such as string concatenation with a Date object or double negation for type coercion. ```javascript /*jslint convert*/ // Allow conversion operator. let foo = new Date() + ""; let bar = !!0; ``` -------------------------------- ### Allow 'this' Keyword with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint this*/` directive to allow the use of the `this` keyword within functions. ```javascript /*jslint this*/ // Allow 'this'. function foo() { return this; } ``` -------------------------------- ### Allow Long Lines with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint long*/` directive to allow lines of code that exceed the default length limit. ```javascript /*jslint long*/ // Allow long lines. let foo = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; ``` -------------------------------- ### Ignore Specific Lines for Code Coverage Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use '//coverage-ignore-line' to exclude a specific line of code from code coverage analysis. This is useful for lines that are intentionally not meant to be covered. ```javascript // JSLint will ignore code-coverage at given line. if (false) { console.log("hello world"); //coverage-ignore-line } ``` -------------------------------- ### Allow Eval Function with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint eval*/` directive to permit the use of the `eval()` function in your JavaScript code. ```javascript /*jslint eval*/ // Allow eval(). eval("1"); ``` -------------------------------- ### Debug CSS Style Report Source: https://github.com/jslint-org/jslint/blob/beta/index.html This function reports on CSS styles that have zero or one match in the document. It helps identify potentially unused or overly broad CSS selectors. ```javascript function dom_style_report_unmatched() { // Debug css-style. let style_list = []; Array.from(document.querySelectorAll("style")).forEach(function (elem) { elem.innerHTML.replace(( /\/\\[[\S\s]*?\*\/|;|\}/g ), "\n").replace(( /^([^\n @].*?)[,{:\].*?$/gm ), function (match0, match1) { let ii; try { ii = document.querySelectorAll(match1).length; } catch (err) { console.error(match1 + "\n" + err); //jslint-ignore-line } if (ii <= 1 && !( /^0 (?:(body > )?(?:\.button|\.readonly|\.styleColorError|\.textarea|\.uiAnimateSlide|a|base64|body|code|div|input|pre|textarea)(?:,| \{))|^[1-9]\d*? #/m ).test(ii + " " + match0)) { style_list.push(ii + " " + match0); } return ""; }); }); style_list.sort().reverse().forEach(function (elem, ii, list) { console.error( //jslint-ignore-line "dom_style_report_unmatched " + (list.length - ii) + ". " + elem ); }); } ``` -------------------------------- ### Allow Unordered Declarations with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint unordered*/` directive to allow unordered cases in switch statements, parameters, properties, variables, and exports. ```javascript /*jslint unordered*/ // Allow unordered cases, params, properties, variables, and exports. let foo = {bb: 1, aa: 0}; function bar({ bb = 1, aa = 0 }) { return aa + bb; } export { foo, bar }; ``` -------------------------------- ### Allow Complex Fat-Arrow Functions with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the `/*jslint fart*/` directive to allow complex fat-arrow functions, including asynchronous operations with destructuring. ```javascript /*jslint fart*/ // Allow complex fat-arrow. let foo = async ({bar, baz}) => { return await bar(baz); }; ``` -------------------------------- ### Declare Global Variables with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use the 'global' directive to declare variables that are expected to be defined globally. This prevents JSLint from flagging them as undeclared. ```javascript /*global foo, bar*/ // Declare global variables foo, bar. foo(); bar(); ``` -------------------------------- ### Ignore Specific Lines with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md Employ '//jslint-ignore-line' to make JSLint ignore non-fatal warnings on a specific line of code. This is helpful for addressing warnings that are understood and accepted. ```javascript // JSLint will ignore non-fatal warnings at given line. eval("1"); //jslint-ignore-line ``` -------------------------------- ### Disable Code Coverage in a Region Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use 'coverage-disable' and 'coverage-enable' directives to exclude specific code blocks from code coverage analysis. This is useful for code paths that are not intended to be covered or tested. ```javascript /*coverage-disable*/ // JSLint will ignore code-coverage in this region. if (false) { console.log("hello world"); } /*coverage-enable*/ ``` -------------------------------- ### Disable JSLint Analysis in a Region Source: https://github.com/jslint-org/jslint/blob/beta/README.md Use 'jslint-disable' and 'jslint-enable' directives to exclude specific code blocks from JSLint analysis. This is useful for code that intentionally violates linting rules or contains syntax errors. ```javascript /*jslint-disable*/ JSLint will ignore and treat this region as blank-lines. Syntax error. /*jslint-enable*/ ``` -------------------------------- ### Restrict Property Access with JSLint Source: https://github.com/jslint-org/jslint/blob/beta/README.md The 'property' directive limits property access to a specified set of properties, enhancing code safety by preventing access to unexpected object properties. ```javascript /*property foo, bar*/ // Restrict property-access to only .foo, .bar. let aa = {bar: 1, foo: 2}; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.