notyf

repository·master·Indexed 25 days ago

https://github.com/caroso1222/notyf

A minimalistic, responsive, and A11Y-compatible vanilla JavaScript toast library for displaying notifications. Lightweight (<3KB gzipped) and dependency-free, it supports modern frameworks including React, Angular, Vue, Svelte, Nuxt, and Aurelia, and is compatible with IE11. Version 3.10.0.

Tokens
6.7K
Snippets
21
Records
35
Agent score
83%

What's inside notyf

  1. Use Notyf globally via `<script>` tags

    master

    To use Notyf without a module bundler, you can include the minified JavaScript and CSS files directly in your HTML.

    1. Install Notyf via npm: npm i notyf.
    2. Copy node_modules/notyf/notyf.min.js and node_modules/notyf/notyf.min.css to your project's public assets folder.
    3. Include the CSS in the <head> of your document.
    4. Include the JS script before the closing </body> tag.

    Important: Ensure you initialize Notyf and any custom scripts after the Notyf script tag is loaded.

    <!DOCTYPE html>
    <html lang="en">
        <head>
            ...
            <link href="path/to/notyf.min.css" rel="stylesheet">
        </head>
        <body>
            <button id="send-button">Send</button>
            ...
            <script src="path/to/notyf.min.js" type="application/javascript"></script>
            <script type="application/javascript">
              var notyf = new Notyf({
                duration: 5000 // Set your global Notyf configuration here
              });
            </script>
            <script src="scripts/your-custom-script.js" type="application/javascript"></script>
        </body>
    </html>
  2. Integrate Notyf with Svelte and Rollup

    master

    To use Notyf in a Svelte project using Rollup, you must configure Rollup to process the Notyf CSS files and then create a singleton instance for use throughout your application.

    1. Install CSS plugin

    Install rollup-plugin-css-only to handle CSS imports from node_modules:

    npm i rollup-plugin-css-only

    2. Configure Rollup

    Update your rollup.config.js to include the css plugin. This configuration reads CSS imports and writes them to a specific vendor file (e.g., public/build/vendor.css).

    3. Include CSS in HTML

    Add a <link> tag to your index.html pointing to the CSS file generated by the Rollup plugin.

    4. Create a Notyf singleton

    Create a notyf.js file to initialize a single instance of Notyf with your desired configuration. You must import the Notyf CSS directly in this file.

    5. Use in Svelte components

    Import your singleton instance into any .svelte component to trigger notifications.

    // 1. rollup.config.js configuration
    import css from 'rollup-plugin-css-only';
    
    export default {
      input: 'src/main.js',
      output: { ... },
      plugins: [
        css({ output: 'public/build/vendor.css' }),
        // ... other plugins
      ]
    };
    
    // 2. notyf.js singleton creation
    import { Notyf } from 'notyf';
    import 'notyf/notyf.min.css';
    
    export const notyf = new Notyf({
      duration: 5000,
      dismissible: true,
    });
    
    // 3. Usage in App.svelte
    <script>
      import { notyf } from './notyf';
    
      function success() {
        notyf.success('It works!')
      }
    </script>
    
    <main>
      <button on:click={success}> Success </button>
    </main>
  3. Integrate Notyf with Angular

    master

    To use Notyf in an Angular application, you must import the minified CSS as an external asset, create an injection token with a factory for dependency injection, and provide that token in your AppModule.

    // 1. Add the stylesheet to angular.json
    {
      "projects": {
        "your-project-name": {
          "architect": {
            "build": {
              "options": {
                "styles": [
                  "src/styles.css",
                  "./node_modules/notyf/notyf.min.css"
                ]
              }
            }
          }
        }
      }
    }
  4. Create Notyf Injection Token and Factory

    master

    Create a file (e.g., notyf.token.ts) to define an InjectionToken and a factory function. The factory allows you to set global configuration for all Notyf instances injected via this token.

    import { InjectionToken } from '@angular/core';
    import { Notyf } from 'notyf';
    
    export const NOTYF = new InjectionToken<Notyf>('NotyfToken');
    
    export function notyfFactory(): Notyf {
      return new Notyf({
        duration: 5000 // Set your global Notyf configuration here
      });
    }
  5. Integrate Notyf with Vue using provide/inject

    master

    To use Notyf globally in a Vue application, provide a single Notyf instance in your main.js file using Vue's provide option. This allows you to consume the Notyf instance in any component using the inject option, avoiding the need to instantiate it multiple times.

    import Vue from 'vue'
    import App from './App.vue'
    import { Notyf } from 'notyf';
    import 'notyf/notyf.min.css';
    
    Vue.config.productionTip = false
    
    new Vue({
      provide: () => {
        return {
          notyf: new Notyf({
            duration: 5000 // Set your global Notyf configuration here
          })
        }
      },
      render: h => h(App),
    }).$mount('#app')
  6. Integrate Notyf with Nuxt.js

    master

    To use Notyf in a Nuxt.js project, you need to create a plugin to make the Notyf instance available globally via this.$notyf in your Vue components. You must also register the Notyf CSS and the plugin in your nuxt.config.js file. Ensure ssr: false is set for the plugin to prevent errors during server-side rendering, as Notyf requires a browser environment.

    // 1. Create ~/plugins/notyf.js
    import { Notyf } from "notyf";
    import Vue from "vue";
    
    const notyf = new Notyf();
    
    Object.defineProperty(Vue.prototype, "$notyf", { value: notyf });
    
    // 2. Update nuxt.config.js
    export default {
      ...
      css: ["notyf/notyf.min.css"],
      ...
      plugins: [{ src: "~/plugins/notyf.js", ssr: false }],
    }
  7. Use Notyf via CDN

    master

    For vanilla JavaScript projects without a build step, you can include the Notyf CSS and JS files directly in your HTML document using jsDelivr.

    <html
      <head>
        ...
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.css">
      </head>
      <body
        ...
        <script src="https://cdn.jsdelivr.net/npm/notyf@3/notyf.min.js"></script>
      </body>
    </html>
  8. Configure Notyf globally in Aurelia

    master

    To use a single, pre-configured Notyf instance across your entire Aurelia application, register it as a singleton in your main.ts or main.js file. This allows you to set global options like duration once.

    After registration, inject Notyf into your components using the @lazy decorator to ensure proper dependency resolution. Access the instance by calling the injected getter function.

    // 1. In main.ts or main.js
    import { Notyf } from 'notyf';
    import 'notyf/notyf.min.css';
    
    // Register as a singleton with global configuration
    aurelia.container.registerSingleton(Notyf,
      () => new Notyf({
        duration: 5000
      })
    );
    
    // 2. In your component
    import {autoinject} from 'aurelia-framework';
    import {lazy} from 'aurelia-framework';
    import {Notyf} from 'notyf';
    
    @autoinject()
    export class Test
    {
      constructor(@lazy(Notyf) private getNotyf: () => Notyf) {}
    
      notifyStuff()
      {
        this.getNotyf().success("Hello World!!!");
      }
    }
  9. Integrate Notyf with React using Context

    master

    To share a single global Notyf instance across your React component tree, use React Context. This prevents creating multiple Notyf instances and ensures consistent configuration (like duration) throughout your application.

    1. Import Styles

    Import the minified Notyf stylesheet in your entry point (e.g., App.js or index.js) to ensure notifications are styled correctly:

    import 'notyf/notyf.min.css';

    2. Create the Notyf Context

    Create a file named NotyfContext.js to initialize the Notyf instance and export the context. By passing the new Notyf() instance directly into React.createContext(), you can use the instance as a default value without needing to wrap your app in a <NotyfContext.Provider>.

    import React from 'react';
    import { Notyf } from 'notyf';
    
    export default React.createContext(
      new Notyf({
        duration: 5000 // Set your global Notyf configuration here
      })
    );

    3. Consume Notyf in Components

    Depending on your React version, use either Hooks or the Context Consumer to access the Notyf instance.

    // For React >= 16.8 (Hooks)
    import React, { useContext } from 'react';
    import NotyfContext from './path/to/NotyfContext';
    
    export function Card() {
      const notyf = useContext(NotyfContext);
      
      return (
        <div>
          <button onClick={() => notyf.error('Please fill out all the fields in the form')}>Send</button>
        </div>
      );
    }
    
    // For React < 16.8 (No Hooks)
    import React from 'react';
    import NotyfContext from './path/to/NotyfContext';
    
    export function Card() {
      return (
        <NotyfContext.Consumer>
          {notyf => (
            <div>
              <button onClick={() => notyf.error('Please fill out all the fields in the form')}>Send</button>
            </div>
          )}
        </NotyfContext.Consumer>
      );
    }
  10. Provide Notyf in AppModule

    master

    Register the NOTYF token in your AppModule providers array using the notyfFactory to enable dependency injection throughout your application.

    import { NOTYF, notyfFactory } from './path/to/notyf.token';
    
    @NgModule({
      declarations: [ ... ],
      imports: [ ... ],
      providers: [
        { provide: NOTYF, useFactory: notyfFactory }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }