Is there a way to stop Babel from transpiling JavaScript and wrapping its output in a define([], function(){}) block?

I am currently working on transpiling ES6 files to ES5 using Babel in order to be compatible with RequireJS (Magento 2). However, I have encountered an issue that has me stuck.

Here is the Babel configuration:

const presets = [
    [
        "@babel/env",
        {
            "targets": {
                "edge": "17",
                "firefox": "60",
                "chrome": "67",
                "safari": "11.1",
                "ie": "11"
            },
            "useBuiltIns": "entry",
            "corejs": "3",
            "modules": 'cjs'
        }
    ]
];

const plugins = [
    [
        "@babel/plugin-transform-runtime",
        {
            "regenerator": true,
            "useESModules": false,
            "helpers": false
        },
    ]
]

module.exports = { presets, plugins };

Package.json content:

    "name": "project",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "directories": {
        "test": "test"
    },
    "scripts": {
        "build": "babel --plugins @babel/plugin-transform-modules-amd web/js/source --out-dir web/js/build && terser-folder web/js/build -e -o web/js/build -x .js",
        "watch": "babel --plugins @babel/plugin-transform-modules-amd --watch web/js/source --out-dir web/js/build"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "@babel/cli": "^7.13.10",
        "@babel/core": "^7.13.10",
        "@babel/preset-env": "^7.13.5",
        "terser-folder": "^2.0.0"
    },
    "dependencies": {
        "@babel/plugin-transform-runtime": "^7.14.5",
        "@babel/runtime": "^7.14.0"
    }
}

In Magento, JavaScript files typically resemble this structure:

define([
        'jquery',
        'matchMedia',
    ],
    function($, matchMedia) {
        /* SCRIPTS HERE */
    }
)

My goal is to incorporate ES6 features like arrow functions, const, let, etc., into these files. However, when I transpile them with Babel, it adds an additional define wrapper around the entire transpiled file as shown below:

define([], function () {
  "use strict";

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

  define(['jquery', 'matchMedia'], function ($, matchMedia) {
     /* TRANSPILED SCRIPTS HERE */
  });
});

While removing the outer define resolves the issue, it is cumbersome to do so manually every time I compile a file. Is there a specific setting that prevents this outer define from being included?

Answer №1

ES6 introduces two different processing modes:

  1. ""script"" - This mode is triggered when a file is loaded using a , or any other standard ES5 method of loading files
  2. ""module"" - This mode is activated when a file is treated as an ES6 module For more information, check out:

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

Display an image in an Angular application using a secure URL

I am trying to return an image using a blob request in Angular and display it in the HTML. I have implemented the following code: <img [src]="ImageUrl"/> This is the TypeScript code I am using: private src$ = new BehaviorSubject(this.Url); data ...

Drawbacks of adjusting design according to screen width via javascript detection

When creating a website, I want it to be compatible with the most common screen resolutions. Here is my proposed method for achieving this: -Develop CSS classes tailored to each screen resolution, specifying properties such as width and position. -Write ...

My iPad is acting up and the .click() function seems to be malfunctioning, but only within

Currently dealing with a perplexing and frustrating issue - I've implemented a .click() event in a view of my backbone.js application (my first time doing so), and while it works perfectly in all desktop browsers, it simply refuses to work on the iPad ...

Finding specific data in sessionStorage using an ID or key

I have stored data in sessionStorage and this is an example of how I save the data: $.ajax({ type: 'POST', url: 'Components/Functions.cfc?method='+cfMethod, data: formData, dataType: 'json' }).done(function(ob ...

The problem with JQuery ajax arises when attempting to send a file input value

I am facing an issue when trying to send a file value to PHP using the ajax code below. The file gets uploaded successfully and stored in the database, but the problem arises when I get redirected. // form data submission $('#myForm').submit(fun ...

What's the best way to modify the style property of a button when it's clicked in

I am working with a react element that I need to hide when a button is clicked. The styles for the element are set in the constructor like this: constructor(props) { super(props); this.state = { display: 'block' }; this. ...

Using Node.js to efficiently parse JSON data into customizable PUG templates

I have a challenge where I am parsing JSON data into elements called homeCards. To achieve this, I use Axios to request the JSON data and then utilize a for loop to cycle through it. Inside my Axios function, I extract the fields I need and store them in v ...

Using express.static can cause an issue with a Nodejitsu application

I'm completely puzzled by this issue that keeps cropping up. Whenever I try to add a static path to my app, I encounter an error on the hosting platform I use called "nodejitsu". The error message indicates that the application is not functioning prop ...

Errors have been observed when using JavaScript variables that begin with the symbol $

For the longest time, I've used JavaScript variable names that begin with $ to signify that they hold jQuery values. For example: $buttons = $( 'button' ); However, a couple of nights ago, I encountered an issue when loading the page in the ...

Guidelines for accessing a specific object or index from a dropdown list filled with objects stored in an array

Here is a question for beginners. Please be kind. I have created a select field in an HTML component using Angular, populated from an array of objects. My goal is to retrieve the selection using a method. However, I am facing an issue where I cannot use ...

What is the best way to transfer data from processing.js to a rails application?

I am working on a basic canvas project using processing.js, and I am wondering how I can transfer data from my Rails application to Processing.js. void drawBox(int bx, int by, int bs, int bs){ strokeWeight(3); stroke(50,50,50); // Test ...

Leverage Firebase cloud functions to transmit a POST request to a server that is not affiliated with

Is it feasible to utilize a firebase cloud function for sending a post request to a non-Google server? It appears that being on the blaze plan is necessary in order to communicate with non-google servers. Essentially, I aim to perform a POST action to an ...

Next.js server component allows for the modification of search parameters without causing a re-fetch of the data

I have a situation where I need to store form values in the URL to prevent data loss when the page is accidentally refreshed. Here's how I am currently handling it: // Form.tsx "use client" export default function Form(){ const pathname ...

Dynamically insert innerHTML content into table rows using JavaScript in PHP is a fantastic way to customize

Having trouble with innerHTML in this scenario, looking to achieve something along these lines: <table width="100%" border="0" id="table2"> <?php include("connection.php"); $sql=mysql_query("select* from b1"); while($res=mys ...

Watcher doesn't detect modifications in array values

I am working with a basic array structure that looks like this: dates[2] 0:"2018-01-09T15:00:00.000Z" 1:"2018-01-10T14:00:00.000Z" My watcher is configured as follows: data() { return { dates: [], } } watch: { // this fu ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

Comparing textboxes on separate web pages to validate forms using AJAX on the server side

I am exploring the creation of a straightforward server-side form validation system using ajax. The objective is to verify if the data inputted by the user matches the data stored on another page. For instance, if a user enters the number 10 in a textbox ...

Issue with NextJs query parameters receiving incorrect values upon dynamic updates

On my page, there are default query parameters set as '?status=default' I'm attempting to retrieve the status value dynamically change it using a button trigger Initially, when the page loads for the first time, it correctly displays the v ...

Having difficulty reaching elements within a shadow frame using Selenium in Java

I am encountering an issue while trying to access an element within a shadow iframe. I am able to switch to the frame successfully, but when attempting to access elements inside it, I am getting a Stale Element Exception. Any assistance with this would be ...

Converting a Javascript array to an NSArray in Xcode

As a complete beginner to Xcode and programming in general, I recently built an app using javascript and html and integrated it into Xcode. Currently, my main focus is on extracting multiple arrays from the html/javascript file and exporting them as a csv ...