Unable to export JavaScript module

In my JavaScript project, I have a module named utilities stored in a file called utilities.js. This module contains basic functions that I want to keep hidden from the global namespace. I know that in order to achieve this, I need to create a module, export it, import it into the necessary file, and then call its functions. However, I am facing difficulty in properly exporting the module. Despite trying various methods, I keep encountering errors. Below is the code snippet that is causing the issue:

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 };

The error message I am receiving is:

application.js:12560 Uncaught SyntaxError: Unexpected token export

Answer №1

Give this a shot:

const helperFunctions = function() {
  return {
    throttle: 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 helperFunctions;

or

function helperFunctions() {
  return {
    throttle: 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.helperFunctions = helperFunctions;  

Answer №2

It appears that you are conducting server-side exporting. In order to utilize the export keyword, you must transpile with babel. For guidance on setting it up, please refer to this https://babeljs.io/setup#installation

On the client-side, you can configure it with webpack, which also requires babel transpilation.

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

Answer №3

If you're working with Node.js, everything should be running smoothly. However, if you're coding for the browser, remember to include <script type="module"> in order to utilize the export keyword (ES modules). Alternatively, you can always transpile your code with Babel.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There seems to be a glitch with jQuery on my Angular.js website

I'm trying to implement Masonry.js on my website, and although I've managed to make it work, the solution feels like a messy workaround and I can't quite figure out why it's functioning (and not functioning well). The primary issues I& ...

Safari is not properly handling element IDs when used in conjunction with React

I am currently in the process of building a straightforward single-page website utilizing React. At the top of the page, there is a navigation bar that contains links to various sections of the site: <li><a href="/#about">About u ...

Creating a vertical bar chart in D3 with a JSON data source embedded within the code

Struggling to generate a stacked bar graph in D3.js. The axes are displaying correctly, but the data on the graph is not showing up. Any suggestions on what could be causing this issue? JS: var svg = d3.select("#recovery__table"), margin = {top: 20, ...

React - Attempting to access property X from an undefined variable

Trying to access the string in section1.text, but my console is showing: https://i.stack.imgur.com/ox8VD.png Here's the JSX code I'm using: return ( <div> <h1>{this.props.article.title}</h1> ...

Google's AJAX crawling scheme using the shebang syntax is failing to crawl pages

I have incorporated Google's shebang '#!' syntax for ajax crawling on my website. Both ends of the system have been set up as per the guidelines provided at https://developers.google.com/webmasters/ajax-crawling/docs/specification This mea ...

What is the reason behind console.log() displaying an array, while typeof returning 'object'?

This question pertains to the outcome of a mongoose find() operation. After running the code console.log('apparently this is an ' + typeof campaign.advertGroups, campaign.advertGroups); The resulting output is as follows: apparently this is an ...

Troubleshooting Browser Behavior: Back Button Not Loading Page - jQuery and HTML5

I've built a dynamic slideshow using jQuery to change images with seamless transitions. To enhance user experience, I'm also updating the page title and URL without triggering a page reload. The code snippet below illustrates how I achieve this: ...

Grouping various event listeners within a v-for loop

My Desired Outcome In my Vue component, I am displaying a list of actions using v-for. Each action should have a corresponding @click event handler that triggers the action method within the component. I need help declaring these actions in my data() fun ...

Error message: Nextjs encounters hydration issue only in the production environment

I've been facing this issue for hours now. I deployed my Next.js application on Vercel and encountered numerous hydration errors there. Interestingly, in my local development environment, I don't experience any errors at all. I came across sugge ...

Use Google script to input drop down options directly into a Google spreadsheet

After gathering coding advice from various StackOverflow examples, I've hit a roadblock while attempting to take my script to the next level. The task seems simple enough, but for some reason, I just can't figure it out. Here's the situati ...

Creating clickable phone numbers in JSON elements for browser display to enable direct calling action

There is a Phone.json file with the following contents: { "Call": "Hi, Please contact the custom care at (119)239-9999 for further discussions" }, { "Call": " For emergency dial 911 as soon as possible" } The goal is to dis ...

The error of 'illegal invocation' occurs when attempting to use input setCustomValidity with TypeScript

I am new to the Typescript world and currently converting one of my first React applications. I am facing an issue while trying to set custom messages on input validation using event.target.setCustomValidity. I keep getting an 'Illegal invocation&apo ...

Converting an array of objects into a dictionary using TypeScript

I'm attempting to convert an array of objects into a dictionary using TypeScript. Below is the code I have written: let data = [ {id: 1, country: 'Germany', population: 83623528}, {id: 2, country: 'Austria', population: 897555 ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

How can I load 3-D models in three.js by specifying file content instead of the file path?

I'm looking to develop an interactive online model viewer that allows users to easily upload and view models without having to manually edit the source code. Unfortunately, most browsers restrict access to file paths, but can still read file contents. ...

Ensure that a new window is opened while maintaining the exact location of the parent window

Having an issue with printing a calendar. The problem arises when trying to load CSS with absolute paths like /path/to/css.css. Opening a window with: var win = open('', '_blank') win.document.write(htmlContent) will display the HTML ...

Jest test encounters an error due to an unexpected token, looking for a semicolon

I've been working on a Node project that utilizes Typescript and Jest. Here's the current project structure I have: https://i.stack.imgur.com/TFgdQ.png Along with this tsconfig.json file "compilerOptions": { "target": "ES2017", "modu ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

Updating the background color using typescript

Before transitioning to angular development, I had experience working with vanilla Javascript. I encountered a challenge when trying to modify the css properties of specific elements using Typescript. Unfortunately, the traditional approach used in Javascr ...

"Encountering issues with running a MongoDB aggregate query involving date fields

I have been attempting to retrieve data from MongoDB using an aggregate query in Node.js for a specific date range. let date = '20230925' let year = date.slice(0, 4); let month = String(date.slice(4, 6)).padStart(2, '0'); ...