tiny-invariant

repository·master·Indexed 23 days ago

https://github.com/alexreardon/tiny-invariant

A minimal, zero-dependency alternative to the invariant package for environments where bundle size is critical. It provides an invariant function to assert conditions, supports type narrowing in TypeScript and Flow, and uses template literals for message formatting. In production mode, custom messages are replaced with 'Invariant failed' to reduce bundle size.

Tokens
878
Snippets
5
Records
8
Agent score
34%

What's inside tiny-invariant

  1. Format error messages with template literals

    master

    Unlike the standard invariant package which uses sprintf style formatting, tiny-invariant avoids internal formatting logic to keep the bundle size small. Instead, you should use JavaScript template literals to format your messages.

    invariant(condition, `Hello, ${name} - how are you today?`);
  2. Optimize bundle size by dropping messages

    master

    To achieve maximum KB savings, you can configure your build pipeline to strip out the message strings in production. This allows your bundler to tree-shake the unused message code when process.env.NODE_ENV is 'production'.

    Recommended tools:

    • Babel: Use babel-plugin-dev-expression.
    • TypeScript: Use tsdx (or run babel-plugin-dev-expression after compilation).
    • Rollup: Use rollup-plugin-replace to set NODE_ENV to production.
    • Webpack: Follow standard production mode instructions.
  3. Narrow types using `tiny-invariant`

    master

    tiny-invariant works with TypeScript and Flow to perform type narrowing. If you assert that a value is not null using invariant, the type of that value will be narrowed in subsequent lines of code.

    const value: Person | null = { name: 'Alex' }; // type of value == 'Person | null'
    invariant(value, 'Expected value to be a person');
    // type of value has been narrowed to 'Person'
  4. Use `tiny-invariant` to assert conditions

    master

    The invariant function takes a value (the condition). If the value is truthy, the function does nothing. If the value is falsy, it throws an Error. This is useful for asserting that certain conditions must be met for your code to proceed correctly.

    import invariant from 'tiny-invariant';
    
    invariant(truthyValue, 'This should not throw!');
    
    invariant(falsyValue, 'This will throw!');
    // Error('Invariant violation: This will throw!');
  5. Provide efficient error messages

    master

    You can pass a string or a function that returns a string (() => string) as the second argument. Using a function is recommended if the message is expensive to compute, as the function will only be executed if the invariant fails.

    import invariant from 'tiny-invariant';
    
    invariant(condition, `Hello, ${name} - how are you today?`);
    
    // Using a function is helpful when your message is expensive
    invariant(value, () => getExpensiveMessage());