使用 javascript 全局设置 toastr 选项

set toastr options globally using javascript

我有一组全部使用 toastr 的脚本。它们看起来有点像这样:

import $ from 'jquery';
import toastr from 'toastr';
import list from './data/address';
import { selectedApp, validate, getCookie, setCookie } from './common';

$(document).ready(function () {
    toastr.options = {
        'closeButton': true,
        'debug': true,
        'newestOnTop': false,
        'progressBar': true,
        'positionClass': 'toast-top-full-width',
        'preventDuplicates': false,
        'onclick': null,
        'showDuration': '6000',
        'hideDuration': '1000',
        'timeOut': '50000',
        'extendedTimeOut': '1000',
        'showEasing': 'swing',
        'hideEasing': 'linear',
        'showMethod': 'fadeIn',
        'hideMethod': 'fadeOut'
    };

    // ---  Application code --- //
});

我有几个脚本,它们都在顶部声明了 toastr.options。有没有办法(可能使用导入)允许我全局设置 toastr 选项?

如果你想使用es6模块,那么你可以创建一个单独的toastr配置。 例如,

import toastr from "toastr";

toastr.options = {
  closeButton: true,
  debug: true,
  newestOnTop: false,
  progressBar: true,
  positionClass: "toast-top-full-width",
  preventDuplicates: false,
  onclick: null,
  showDuration: "6000",
  hideDuration: "1000",
  timeOut: "50000",
  extendedTimeOut: "1000",
  showEasing: "swing",
  hideEasing: "linear",
  showMethod: "fadeIn",
  hideMethod: "fadeOut"
};

export default toastr;

然后只需在顶部导入此文件而不是 toastr,因为这会配置 toastr 并导出配置的 toastr。作为

import toastr from './PathToAboveFile';

或者如果你想要一个 es5 风格的全局配置使用,

window.toastrOptions = {...}

在单独的 js 文件中,并在每个 html 页面中引用。然后在$(document).ready函数中设置即可。

toastr.options = window.toastrOptions;

由于现在 toastr 选项位于单独的文件中,因此可以集中配置。