Cannon Moyer
Cannon Moyer

Reputation: 3174

Cannot Export JS Module

I've got a module called utilities in a utilities.js file. I am using it for some basic js functions and I want to hide the module from the global namespace. I understand that to do this I should create a module, export it, import it in the needed file, then invoke its functions. However, I cannot seem to properly export the module. I figure this is pretty simple but everything I have tried gives an error. Here is my code:

var utilities = (function(){
return {
    debounce: function(func, wait, immediate){
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    }
}
})();

export { utilities };

My error:

application.js:12560 Uncaught SyntaxError: Unexpected token export

Upvotes: 0

Views: 978

Answers (3)

dankobgd
dankobgd

Reputation: 416

this works fine in nodejs, if you are using browser script you need to have <script type="module"> to use export keyword (es modules) or just transpile your code with babel

Upvotes: 0

duc mai
duc mai

Reputation: 1422

it seems that you are exporting on server side. To use export keyword you need to transpile with babel. you can refer to this https://babeljs.io/setup#installation to learn how to set it up

for clientside you can set it up with webpack for example, it also needs babel transpile

npm install --save-dev babel-core
npm install @babel/preset-env --save-dev

Upvotes: 0

Milenko Jevremovic
Milenko Jevremovic

Reputation: 1056

Try:

const utilities = function() {
  return {
    debounce: function(func, wait, immediate){
      var timeout;
        return function() {
          var context = this, args = arguments;
          var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
          };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
       };
     }
   }
 }

export default utilities;

or

function utilities() {
  return {
    debounce: function(func, wait, immediate){
      var timeout;
        return function() {
          var context = this, args = arguments;
          var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
          };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
       };
     }
   }
 }

 module.exports.utilities= utilities;  

Upvotes: 1

Related Questions