Home > database >  Typewriter is not working when loaded via npm import (compiled with Babel)
Typewriter is not working when loaded via npm import (compiled with Babel)

Time:08-18

I set up Typewriter on a site, it works fine when loaded via the direct src.

<script src="https://unpkg.com/[email protected]/dist/core.js"></script>

<script>
    window.addEventListener('DOMContentLoaded', () => {document.getElementById('typewriter-container');
        const typewriter = new Typewriter(whatever, { ... });
...

But when I do it with npm, it doesn't work.

What does "doing it with npm" mean?

Well, since loading stuff the traditional way seems to be outdated... I'm doing the same thing with npm and using the import into a file:

src/typewriter.js

import Typewriter from 'typewriter-effect/dist/core';

And then compiling this file with webpack and babel, and loading that file instead.

<script src="/my_site_stuff/dist/typewriter.js"></script>

This is the compiled file:

dist/typewriter.js

/******/ (function() { // webpackBootstrap
/******/    var __webpack_modules__ = ({

/***/ "./node_modules/typewriter-effect/dist/core.js":
/*!*****************************************************!*\
  !*** ./node_modules/typewriter-effect/dist/core.js ***!
  \*****************************************************/
/***/ (function(module, exports, __webpack_require__) {

/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

!function (e, t) {
  "object" == ( false ? 0 : _typeof(exports)) && "object" == ( false ? 0 : _typeof(module)) ? module.exports = t() :  true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (t),
        __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
        (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
        __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0;
}("undefined" != typeof self ? self : this, function () {
  return function () {
    var e = {
      75: function _(e) {
        (function () {
          var t, n, r, o, a, s;
          "undefined" != typeof performance && null !== performance && performance.now ? e.exports = function () {
            return performance.now();
          } : "undefined" != typeof process && null !== process && process.hrtime ? (e.exports = function () {
            return (t() - a) / 1e6;
          }, n = process.hrtime, o = (t = function t() {
            var e;
            return 1e9 * (e = n())[0]   e[1];
          })(), s = 1e9 * process.uptime(), a = o - s) : Date.now ? (e.exports = function () {
            return Date.now() - r;
          }, r = Date.now()) : (e.exports = function () {
            return new Date().getTime() - r;
          }, r = new Date().getTime());
        }).call(this);
      },
      4087: function _(e, t, n) {
        for (var r = n(75), o = "undefined" == typeof window ? n.g : window, a = ["moz", "webkit"], s = "AnimationFrame", i = o["request"   s], u = o["cancel"   s] || o["cancelRequest"   s], l = 0; !i && l < a.length; l  ) {
          i = o[a[l]   "Request"   s], u = o[a[l]   "Cancel"   s] || o[a[l]   "CancelRequest"   s];
        }

        if (!i || !u) {
          var c = 0,
              p = 0,
              d = [];
          i = function i(e) {
            if (0 === d.length) {
              var t = r(),
                  n = Math.max(0, 16.666666666666668 - (t - c));
              c = n   t, setTimeout(function () {
                var e = d.slice(0);
                d.length = 0;

                for (var t = 0; t < e.length; t  ) {
                  if (!e[t].cancelled) try {
                    e[t].callback(c);
                  } catch (e) {
                    setTimeout(function () {
                      throw e;
                    }, 0);
                  }
                }
              }, Math.round(n));
            }

            return d.push({
              handle:   p,
              callback: e,
              cancelled: !1
            }), p;
          }, u = function u(e) {
            for (var t = 0; t < d.length; t  ) {
              d[t].handle === e && (d[t].cancelled = !0);
            }
          };
        }

        e.exports = function (e) {
          return i.call(o, e);
        }, e.exports.cancel = function () {
          u.apply(o, arguments);
        }, e.exports.polyfill = function (e) {
          e || (e = o), e.requestAnimationFrame = i, e.cancelAnimationFrame = u;
        };
      }
    },
        t = {};

    function n(r) {
      var o = t[r];
      if (void 0 !== o) return o.exports;
      var a = t[r] = {
        exports: {}
      };
      return e[r].call(a.exports, a, a.exports, n), a.exports;
    }

    n.n = function (e) {
      var t = e && e.__esModule ? function () {
        return e.default;
      } : function () {
        return e;
      };
      return n.d(t, {
        a: t
      }), t;
    }, n.d = function (e, t) {
      for (var r in t) {
        n.o(t, r) && !n.o(e, r) && Object.defineProperty(e, r, {
          enumerable: !0,
          get: t[r]
        });
      }
    }, n.g = function () {
      if ("object" == (typeof globalThis === "undefined" ? "undefined" : _typeof(globalThis))) return globalThis;

      try {
        return this || new Function("return this")();
      } catch (e) {
        if ("object" == (typeof window === "undefined" ? "undefined" : _typeof(window))) return window;
      }
    }(), n.o = function (e, t) {
      return Object.prototype.hasOwnProperty.call(e, t);
    };
    var r = {};
    return function () {
      "use strict";

      n.d(r, {
        default: function _default() {
          return S;
        }
      });
      var e = n(4087),
          t = n.n(e);

      var o = function o(e) {
        return new RegExp(/<[a-z][\s\S]*>/i).test(e);
      },
          a = function a(e) {
        var t = document.createElement("div");
        return t.innerHTML = e, t.childNodes;
      },
          s = function s(e, t) {
        return Math.floor(Math.random() * (t - e   1))   e;
      };

      var i = "TYPE_CHARACTER",
          u = "REMOVE_CHARACTER",
          l = "REMOVE_ALL",
          c = "REMOVE_LAST_VISIBLE_NODE",
          p = "PAUSE_FOR",
          d = "CALL_FUNCTION",
          f = "ADD_HTML_TAG_ELEMENT",
          v = "CHANGE_DELETE_SPEED",
          h = "CHANGE_DELAY",
          m = "CHANGE_CURSOR",
          y = "PASTE_STRING",
          g = "HTML_TAG";

      function E(e, t) {
        var n = Object.keys(e);

        if (Object.getOwnPropertySymbols) {
          var r = Object.getOwnPropertySymbols(e);
          t && (r = r.filter(function (t) {
            return Object.getOwnPropertyDescriptor(e, t).enumerable;
          })), n.push.apply(n, r);
        }

        return n;
      }

      function w(e) {
        for (var t = 1; t < arguments.length; t  ) {
          var n = null != arguments[t] ? arguments[t] : {};
          t % 2 ? E(Object(n), !0).forEach(function (t) {
            N(e, t, n[t]);
          }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : E(Object(n)).forEach(function (t) {
            Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));
          });
        }

        return e;
      }

      function T(e) {
        return function (e) {
          if (Array.isArray(e)) return b(e);
        }(e) || function (e) {
          if ("undefined" != typeof Symbol && null != e[Symbol.iterator] || null != e["@@iterator"]) return Array.from(e);
        }(e) || function (e, t) {
          if (e) {
            if ("string" == typeof e) return b(e, t);
            var n = Object.prototype.toString.call(e).slice(8, -1);
            return "Object" === n && e.constructor && (n = e.constructor.name), "Map" === n || "Set" === n ? Array.from(e) : "Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n) ? b(e, t) : void 0;
          }
        }(e) || function () {
          throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
        }();
      }

      function b(e, t) {
        (null == t || t > e.length) && (t = e.length);

        for (var n = 0, r = new Array(t); n < t; n  ) {
          r[n] = e[n];
        }

        return r;
      }

      function A(e, t) {
        for (var n = 0; n < t.length; n  ) {
          var r = t[n];
          r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);
        }
      }

      function N(e, t, n) {
        return t in e ? Object.defineProperty(e, t, {
          value: n,
          enumerable: !0,
          configurable: !0,
          writable: !0
        }) : e[t] = n, e;
      }

      var S = function () {
        function n(r, E) {
          var b = this;
          if (function (e, t) {
            if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
          }(this, n), N(this, "state", {
            cursorAnimation: null,
            lastFrameTime: null,
            pauseUntil: null,
            eventQueue: [],
            eventLoop: null,
            eventLoopPaused: !1,
            reverseCalledEvents: [],
            calledEvents: [],
            visibleNodes: [],
            initialOptions: null,
            elements: {
              container: null,
              wrapper: document.createElement("span"),
              cursor: document.createElement("span")
            }
          }), N(this, "options", {
            strings: null,
            cursor: "|",
            delay: "natural",
            pauseFor: 1500,
            deleteSpeed: "natural",
            loop: !1,
            autoStart: !1,
            devMode: !1,
            skipAddStyles: !1,
            wrapperClassName: "Typewriter__wrapper",
            cursorClassName: "Typewriter__cursor",
            stringSplitter: null,
            onCreateTextNode: null,
            onRemoveNode: null
          }), N(this, "setupWrapperElement", function () {
            b.state.elements.container && (b.state.elements.wrapper.className = b.options.wrapperClassName, b.state.elements.cursor.className = b.options.cursorClassName, b.state.elements.cursor.innerHTML = b.options.cursor, b.state.elements.container.innerHTML = "", b.state.elements.container.appendChild(b.state.elements.wrapper), b.state.elements.container.appendChild(b.state.elements.cursor));
          }), N(this, "start", function () {
            return b.state.eventLoopPaused = !1, b.runEventLoop(), b;
          }), N(this, "pause", function () {
            return b.state.eventLoopPaused = !0, b;
          }), N(this, "stop", function () {
            return b.state.eventLoop && ((0, e.cancel)(b.state.eventLoop), b.state.eventLoop = null), b;
          }), N(this, "pauseFor", function (e) {
            return b.addEventToQueue(p, {
              ms: e
            }), b;
          }), N(this, "typeOutAllStrings", function () {
            return "string" == typeof b.options.strings ? (b.typeString(b.options.strings).pauseFor(b.options.pauseFor), b) : (b.options.strings.forEach(function (e) {
              b.typeString(e).pauseFor(b.options.pauseFor).deleteAll(b.options.deleteSpeed);
            }), b);
          }), N(this, "typeString", function (e) {
            var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null;
            if (o(e)) return b.typeOutHTMLString(e, t);

            if (e) {
              var n = b.options || {},
                  r = n.stringSplitter,
                  a = "function" == typeof r ? r(e) : e.split("");
              b.typeCharacters(a, t);
            }

            return b;
          }), N(this, "pasteString", function (e) {
            var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null;
            return o(e) ? b.typeOutHTMLString(e, t, !0) : (e && b.addEventToQueue(y, {
              character: e,
              node: t
            }), b);
          }), N(this, "typeOutHTMLString", function (e) {
            var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null,
                n = arguments.length > 2 ? arguments[2] : void 0,
                r = a(e);
            if (r.length > 0) for (var o = 0; o < r.length; o  ) {
              var s = r[o],
                  i = s.innerHTML;
              s && 3 !== s.nodeType ? (s.innerHTML = "", b.addEventToQueue(f, {
                node: s,
                parentNode: t
              }), n ? b.pasteString(i, s) : b.typeString(i, s)) : s.textContent && (n ? b.pasteString(s.textContent, t) : b.typeString(s.textContent, t));
            }
            return b;
          }), n;
      }();
    }(), r.default;
  }();
});

/***/ })

/******/    });
/************************************************************************/
/******/    // The module cache
/******/    var __webpack_module_cache__ = {};
/******/    
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/        // Check if module is in cache
/******/        var cachedModule = __webpack_module_cache__[moduleId];
/******/        if (cachedModule !== undefined) {
/******/            return cachedModule.exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = __webpack_module_cache__[moduleId] = {
/******/            id: moduleId,
/******/            loaded: false,
/******/            exports: {}
/******/        };
/******/    
/******/        // Execute the module function
/******/        __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/    
/******/        // Flag the module as loaded
/******/        module.loaded = true;
/******/    
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/    
/************************************************************************/
/******/    /* webpack/runtime/compat get default export */
/******/    !function() {
/******/        // getDefaultExport function for compatibility with non-harmony modules
/******/        __webpack_require__.n = function(module) {
/******/            var getter = module && module.__esModule ?
/******/                function() { return module['default']; } :
/******/                function() { return module; };
/******/            __webpack_require__.d(getter, { a: getter });
/******/            return getter;
/******/        };
/******/    }();
/******/    
/******/    /* webpack/runtime/define property getters */
/******/    !function() {
/******/        // define getter functions for harmony exports
/******/        __webpack_require__.d = function(exports, definition) {
/******/            for(var key in definition) {
/******/                if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/                    Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/                }
/******/            }
/******/        };
/******/    }();
/******/    
/******/    /* webpack/runtime/hasOwnProperty shorthand */
/******/    !function() {
/******/        __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/    }();
/******/    
/******/    /* webpack/runtime/make namespace object */
/******/    !function() {
/******/        // define __esModule on exports
/******/        __webpack_require__.r = function(exports) {
/******/            if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/                Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/            }
/******/            Object.defineProperty(exports, '__esModule', { value: true });
/******/        };
/******/    }();
/******/    
/******/    /* webpack/runtime/node module decorator */
/******/    !function() {
/******/        __webpack_require__.nmd = function(module) {
/******/            module.paths = [];
/******/            if (!module.children) module.children = [];
/******/            return module;
/******/        };
/******/    }();
/******/    
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
!function() {
"use strict";
/*!*************************************!*\
  !*** ./src/js/typewriter-effect.js ***!
  \*************************************/
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! typewriter-effect/dist/core */ "./node_modules/typewriter-effect/dist/core.js");
/* harmony import */ var typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0__);

}();
/******/ })()
;
//# sourceMappingURL=typeWriter.js.map

How do I know what the problem is?

CodePudding user response:

Webpack encloses everything in the compiled file so nothing leaks into the global scope.

You'd have to change your src file and do:

import Typewriter from 'typewriter-effect/dist/core';

window.Typewriter = Typewriter;

Then, when using it, instead of:

const typewriter = new Typewriter(...);

Just do:

const typewriter = new window.Typewriter(...);

What we are doing here is, making it available to the global scope.

  •  Tags:  
  • npm
  • Related