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?