es-check

repository·main·Indexed 42 days ago

https://github.com/yowainwright/es-check

A tool for validating that JavaScript files adhere to a specific ECMAScript version. It verifies that build processes have correctly converted modern syntax into a target version compatible with specific environments. Features include CLI and programmatic Node.js usage, browser compatibility checks via browserslist, TypeScript support, and polyfill detection. Version 9.8.0.

Tokens
22.3K
Snippets
84
Records
106
Agent score
52%

What's inside es-check

  1. Perform browser feature checks using Browserslist

    main

    To check detected ES features against specific target browsers, enable both checkBrowser and checkFeatures. You can specify the target browsers using browserslistQuery within your configuration file.

    {
      "checkBrowser": true,
      "checkFeatures": true,
      "browserslistQuery": "last 2 versions",
      "files": ["dist/**/*.js"]
    }
  2. Understand the documentation site structure

    main

    The Astro-based project follows this directory structure:

    • /src/pages: Contains the page routes.
    • /src/content/docs: Stores the documentation content as .mdx files.
    • /src/components: Contains reusable UI components.
    • /src/layouts: Contains page layouts.
    • /public: Stores static assets.
  3. Handle polyfills during feature checking

    main

    When using polyfills like core-js, es-check might flag modern features as errors. Use these options to manage polyfill detection:

    • --checkForPolyfills: Automatically detects common polyfill patterns (e.g., core-js imports or common methods for Array, String, Object, Promise, and RegExp).
    • --ignorePolyfillable: Ignores all features that can be polyfilled, or limits the scope to a specific library (e.g., --ignorePolyfillable=core-js).
    • --allowList: Explicitly allows specific features regardless of the target ES version.
    • --ignore: Completely ignores specific features (use as a temporary measure).
    # Automatic detection
    es-check es2022 './dist/**/*.js' --checkFeatures --checkForPolyfills
    
    # Explicitly allow specific features
    es-check es2022 './dist/**/*.js' --checkFeatures --allowList="ArrayToSorted,ObjectHasOwn"
    
    # Ignore all polyfillable features
    es-check es2017 './dist/**/*.js' --checkFeatures --ignorePolyfillable
  4. Understand ES Check error messages

    main

    When ES Check identifies incompatible JavaScript features, it outputs a failure report containing the file path, the specific error description, the line and column number, and a snippet of the offending code.

    Basic Error Format:

    ✗ ES Check failed!
    ./dist/app.js
      - error: Arrow function is not supported in ES5
      - line: 42:15
      - code: const sum = (a, b) => a + b;

    If multiple errors exist in a file, they are listed sequentially with their respective details.

  5. Use multiple configurations for different bundle types

    main

    If your project produces multiple formats (e.g., CJS, ESM, UMD), you can provide an array of configuration objects in your .escheckrc file. es-check will apply each configuration to its respective files.

    [
      {
        "ecmaVersion": "es6",
        "module": false,
        "files": "{cjs,umd}/index.{cjs,js}"
      },
      {
        "ecmaVersion": "es2020",
        "module": true,
        "files": "esm/index.mjs",
        "checkFeatures": true
      },
      {
        "files": "legacy/*.js",
        "checkBrowser": true,
        "browserslistEnv": "legacy"
      }
    ]
  6. Perform Feature-Level Browser Checks

    main

    Mapping browsers to a single ES version can be imprecise. To ensure every detected feature (syntax and APIs) is supported by your target browsers, combine --checkBrowser with --checkFeatures.

    This mode uses MDN browser-compat-data to verify that specific features (like Object.hasOwn) are available in the exact browser versions resolved by Browserslist.

    es-check checkBrowser ./dist/**/*.js --checkFeatures
  7. How ES Check works

    main

    ES Check validates JavaScript files against a target ES version using the following process:

    1. AST Parsing: Uses acorn to perform full AST parsing of the input files.
    2. Syntax Validation: Checks if the code is syntactically valid for the target version.
    3. Feature Checking: If the --checkFeatures flag is used, it performs an AST walk to ensure specific ES features are present/valid.
    4. Polyfill Handling:
      • If features are invalid, it checks if they are polyfillable (if --ignorePolyfillable is used).
      • It can also check for the presence of polyfills if --checkForPolyfills is enabled.
    5. Exit Codes: Returns 0 on success and 1 on failure (syntax error or unsupported feature).
  8. Configure build tools for ES compatibility

    main

    If ES Check is failing, ensure your build pipeline is correctly transpiling code to the target version.

    Webpack

    Ensure babel-loader is configured with the correct @babel/preset-env targets (e.g., ie: 11 for ES5):

    module.exports = {
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: "babel-loader",
              options: {
                presets: [
                  [
                    "@babel/preset-env",
                    {
                      targets: { ie: 11 },
                    },
                  ],
                ],
              },
            },
          },
        ],
      },
    };

    Babel

    Verify your .babelrc targets:

    {
      "presets": [
        [
          "@babel/preset-env",
          {
            "targets": {
              "browsers": ["last 2 versions", "ie >= 11"]
            }
          }
        ]
      ]
    }

    TypeScript

    Ensure your tsconfig.json has the correct target and lib settings:

    {
      "compilerOptions": {
        "target": "ES5",
        "lib": ["ES5", "DOM"]
      }
    }
    // Webpack example
    module.exports = {
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: "babel-loader",
              options: {
                presets: [["@babel/preset-env", { targets: { ie: 11 } }]],
              },
            },
          },
        ],
      },
    };
  9. Optimize glob patterns and file selection

    main

    How you select files significantly impacts performance.

    • Use specific patterns: Targeting specific directories is more efficient than broad wildcards.
    • Avoid overly broad globs: Using patterns like './**/*.js' with --not='node_modules' is less efficient than explicitly defining the directories to include.
    • Check bundled files: Running es-check on a single large bundle is faster than running it on many small individual source files.
    • Pre-filter with shell commands: For complex exclusions, use tools like find to pass a specific list of files to es-check via xargs.
    # Good - specific patterns
    es-check es5 './dist/**/*.js' './lib/**/*.js'
    
    # Less efficient - overly broad
    es-check es5 './**/*.js' --not='node_modules'
    
    # Faster - one large file
    es-check es5 './dist/bundle.min.js'
    
    # Pre-filtering with shell
    find ./dist -name "*.js" -not -path "*/vendor/*" | xargs es-check es5
  10. Optimize performance with batching and caching

    main

    For large projects, you can tune es-check performance using the following settings:

    • File Caching: Enabled by default. Disable it using --noCache.
    • Batch Processing: Use --batchSize to control how many files are processed in parallel. This helps manage memory usage in constrained environments.
    ScenarioRecommended --batchSizeReason
    Small codebases (< 100 files)0 (unlimited)Maximum parallelism for fastest results
    Medium codebases (100-500 files)0 or 50Balance between speed and memory
    Large codebases (> 500 files)50-100Prevent memory spikes
    CI/CD with limited memory10-20Conservative memory usage
    Local development0 (default)Utilize available hardware
    # Process 10 files at a time to save memory
    es-check es5 './dist/**/*.js' --batchSize 10