1

I'm creating some classes in ES6 and transpilling it into ES5. But I can't access the objects via ES5.

The ES6 files

import Util from "./utilities";

export default class Dom {
    construtor(){}

    static byId(s){
        if(s !== null) {
            return document.getElementById(s);
        }else{
            throw `${Util.functionName()} needs paramater`;
        }
    }
}

And

export default class Util {
    constructor(){}

    static  functionName(){
        let name = arguments.callee.toString();
        name = name.substr('function '.length);
        name = name.substr(0, name.indexOf('('));

        return name;
    }
}

The one which will be transpiled

import Dom from "./Dom";

console.log(Dom.byId("test"));

The transpiled result

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var _utilities = require("./utilities");

var _utilities2 = _interopRequireDefault(_utilities);

var Dom = (function () {
    function Dom() {
        _classCallCheck(this, Dom);
    }

    _createClass(Dom, [{
        key: "construtor",
        value: function construtor() {}
    }], [{
        key: "byId",
        value: function byId(s) {
            if (s !== null) {
                return document.getElementById(s);
            } else {
                throw _utilities2["default"].functionName() + " needs paramater";
            }
        }
    }]);

    return Dom;
})();

exports["default"] = Dom;
module.exports = exports["default"];

},{"./utilities":3}],2:[function(require,module,exports){

"use strict";

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

var _Dom = require("./Dom");

var _Dom2 = _interopRequireDefault(_Dom);

console.log(_Dom2["default"].byId("h1"));

},{"./Dom":1}],3:[function(require,module,exports){

'use strict';

Object.defineProperty(exports, '__esModule', {
    value: true
});

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var Util = (function () {
    function Util() {
        _classCallCheck(this, Util);
    }

    _createClass(Util, null, [{
        key: 'functionName',
        value: function functionName() {
            var name = arguments.callee.toString();
            name = name.substr('function '.length);
            name = name.substr(0, name.indexOf('('));

            return name;
        }
    }]);

    return Util;
})();

exports['default'] = Util;
module.exports = exports['default'];

},{}]},{},[2])


//# sourceMappingURL=helpers.js.map

So how can I use Dom or Util in normal ES5(console or js file) because I get undefined variable?

Thanks.

Xlander
  • 1,331
  • 12
  • 24
  • 2
    `window.Dom = Dom` ? – Pavlo Oct 06 '15 at 08:40
  • You need a module loader. Babel by default outputs modules in CommonJS syntax so you need one that supports that, e.g. http://stuk.github.io/require1k/ – CodingIntrigue Oct 06 '15 at 08:41
  • @Pavlo `Dom` is not defined on the window scope. It just looks like that from poor indentation – CodingIntrigue Oct 06 '15 at 08:41
  • @Pavlo, Ah yes Thank you very much (I'm so dumb)! Can you put it as answer. – Xlander Oct 06 '15 at 08:43
  • @RGraham, I'm using Babel, babelify and browserify. – Xlander Oct 06 '15 at 08:44
  • @Xlander In that case, `var Dom = require("Dom"); Dom.byId("test");` – CodingIntrigue Oct 06 '15 at 08:45
  • @RGraham will this work in the console? – Pavlo Oct 06 '15 at 08:47
  • @RGraham, I get errors from gulp when trying to do so. – Xlander Oct 06 '15 at 08:48
  • No, but it does cover the "or js file" part. @Xlander I'm not sure what the issue is - what you're doing is fine. http://jsfiddle.net/8m6Lea9c/ – CodingIntrigue Oct 06 '15 at 08:50
  • @RGraham, what I was willing to do is to use all declared function in ES6 in ES5 without transpilling it. In my example the `console.log` is being transpilled that's why it worked but if I add a javascript file after the transpiled script (or console) I can't access the functions. – Xlander Oct 06 '15 at 08:58
  • @Xlander, if you are already using Browserify, I think the answer you were actually looking for is `var Dom = require("Dom").default; Dom.byId("test");`. ES6 default exports behave a bit different than commonjs modules. If you look at the transpiled code, you can see: `module.exports = exports["default"];` – theflowersoftime May 23 '16 at 21:12
  • Or you can use babel's "add-module-exports" plugin. – theflowersoftime May 23 '16 at 21:17

1 Answers1

2

If you want to "export" something to the global scope, assign it to a property of the window object:

window.Dom = Dom;

But beware, declaring global variables are considered bad practice (read why).

Community
  • 1
  • 1
Pavlo
  • 43,301
  • 14
  • 77
  • 113