From f7b9ab2a188b685828c9eded5cc65b25f59bab41 Mon Sep 17 00:00:00 2001 From: Fabio Spampinato Date: Sat, 2 Jan 2021 18:42:15 +0100 Subject: [PATCH] Instantiating LinkifyIt lazily, only if needed --- lib/common/utils.js | 19 +++++++++++++++++++ lib/index.js | 6 ++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/lib/common/utils.js b/lib/common/utils.js index 712cd29..e698b2c 100644 --- a/lib/common/utils.js +++ b/lib/common/utils.js @@ -39,6 +39,24 @@ function arrayReplaceAt(src, pos, newElements) { return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); } +// Sets a property whose initial is computed lazily on an target object +function defineLazyProperty(target, property, instantiator) { + var initied = false; + var value; + Object.defineProperty(target, property, { + get: function () { + if (initied) return value; + initied = true; + value = instantiator(); + return value; + }, + set: function (newValue) { + initied = true; + value = newValue; + } + }); +} + //////////////////////////////////////////////////////////////////////////////// function isValidEntityCode(c) { @@ -300,6 +318,7 @@ exports.lib.mdurl = require('mdurl'); exports.lib.ucmicro = require('uc.micro'); exports.assign = assign; +exports.defineLazyProperty = defineLazyProperty; exports.isString = isString; exports.has = has; exports.unescapeMd = unescapeMd; diff --git a/lib/index.js b/lib/index.js index 7e1f7e4..9a8fe55 100644 --- a/lib/index.js +++ b/lib/index.js @@ -9,7 +9,6 @@ var Renderer = require('./renderer'); var ParserCore = require('./parser_core'); var ParserBlock = require('./parser_block'); var ParserInline = require('./parser_inline'); -var LinkifyIt = require('linkify-it'); var mdurl = require('mdurl'); var punycode = require('punycode'); @@ -288,7 +287,10 @@ function MarkdownIt(presetName, options) { * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.js) * rule. **/ - this.linkify = new LinkifyIt(); + utils.defineLazyProperty(this, 'linkify', function () { + var LinkifyIt = require('linkify-it'); + return new LinkifyIt(); + }); /** * MarkdownIt#validateLink(url) -> Boolean