Is @babel the solution to transpile Array.prototype.flat?

I accidentally caused a backward compatibility issue in my React application by utilizing Array.prototype.flat. I was quite surprised that this problem persisted even after transpiling - I had assumed it would generate es2015-compatible code.

Is there a way to get Babel 7 to properly transpile this? (It seems like in Babel 6, there was a plugin for this but with the emergence of browser support, it may have been discontinued?)

Tools:

The configurations in my top-level files are as follows:

webpack.config.js

var path = require('path')

module.exports = {
  entry: "./src/index.js",
  output: {
      path: path.join(__dirname, 'dist', 'assets'),
      filename: "bundle.js",
      sourceMapFilename: "bundle.map"
  },
  devtool: '#source-map',
  module: {
      rules: [
          {
              test: /\.js$/,
              exclude: /(node_modules)/,
              loader: 'babel-loader'
          }
      ]
  }}

.babelrc

{
  "presets": [ "@babel/preset-env", "@babel/react" ],
  "plugins": [["@babel/plugin-proposal-pipeline-operator", { "proposal": "minimal" }]]
}

.browserslistrc

chrome 58
ie 11

Answer №1

It is crucial to note that you cannot simply "transpile it away"; instead, you must polyfill it.

To achieve this, you can:

  • Install core-js@3 as a runtime dependency
  • Configure @babel/preset-env with useBuiltIns: usage. This will automatically import the necessary polyfills where needed, eliminating the need to manually add import @babel/polyfill in the source code.

The complete .babelrc configuration looks like this:

  "presets": [                                                                                                                                               
    [                                                                                                                                                        
      "@babel/preset-env",                                                                                                                                   
      {                                                                                                                                                      
        "targets": {                                                                                                                                         
          "node": 4                                                                                                                                          
        },                                                                                                                                                   
        "useBuiltIns": "usage",                                                                                                                              
        "corejs": 3                                                                                                                                          
      }                                                                                                                                                      
    ]                                                                                                                                                        
  ]                                                                                                                                                          
}     

Alternatively, you could include @babel/polyfill as a runtime dependency in your package.json and then use import "@babel/polyfill" in your code.

You can find all the necessary information on this page: https://babeljs.io/docs/en/babel-polyfill, but be aware of the nuances involved.

I have provided a simple example to showcase this:

https://github.com/cmdcolin/babel-array-flat-demo

Upon compilation, the correct imports are added to your file found here: https://github.com/cmdcolin/babel-array-flat-demo/blob/master/dist/index.js, and it is compatible with older versions of node.

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

Identifying Oversized Files on Safari Mobile: A Guide to Detecting Ignored Large Files in

Mobile browsers such as Safari have a tendency to ignore large files when passed in through the <input type="file">. For example, testing with a 10mb image file results in no trigger of any events - no change, no error, nothing. The user action is si ...

Enable automatic scrolling on a website using jQuery with the option to pause

I'm trying to implement a feature in jQuery where the web page auto-scrolls to a specific point, pauses for a moment, and then continues scrolling. It's like simulating a user scrolling down a page while reading an article - stopping and starting ...

The Problem of Unspecified Return Type in Vue 3 Functions Using Typescript

Here is the code snippet I am working with: <template> <div> <ul v-if="list.length !== 0"> {{ list }} </ul> </div> </template> < ...

Encountering an error when attempting to add the 'shelljs' module to an Angular 2 TypeScript project

I am facing an issue with including the shelljs library in my Angular 2 TypeScript project. I have already added the shelljs.d.ts file to the node_modules/shelljs directory. Below is my package.json configuration: "name": "myproj1", "description": "myp ...

When combining Angular4, Protractor, Cucumber, TypeScript, and webpack-dev-server, Angular seems to have gone missing

Operating System: macOS Sierra 10.12.4 Node Version: v7.9.0 Npm Version: 5.0.3 Cucumber-js Version: 2.3.0 Protractor Version: 4.0.14 TypeScript Version: 2.2.2 Webpack-dev-server Version: 2.4.5 I encountered an issue while running end-to-end tests. When tr ...

Programmatically searching individual columns in Datatables is a powerful feature that

I am currently working on creating a jQuery datatable with search functionality in each column, using the example provided on the datatables page found at https://datatables.net/examples/api/multi_filter.html Specifically, I want to be able to search the ...

Exploring the Integration of jQuery AJAX in a Contact Form

I would like to incorporate AJAX functionality into a contact form. Here is the current code I have... $("#contact_form").validate({ meta: "validate", submitHandler: function (form) { $('#contact_form').hide(); ...

Modifying the data of a particular object in my rtk asynchronous thunk

I recently started using rtk and immer. I encountered an issue when trying to update my state with redux. For example, when a user logs in, I store their data in redux with the following structure: data = { "user_profile" : { "name&q ...

Leveraging Discord.js to retrieve all messages sent while the bot was inactive

My plan is to create a bot that will store all messages sent in a channel into a txt file on my computer. However, the challenge is that since my computer is not always on when the bot is running, there are gaps in the stored messages in the .txt file. I a ...

Vue Router does not enforce redirects

I am currently facing an issue where the requireAuth() function is being called repeatedly, causing a loop. I only want to display pages when the user is logged in. This is the code snippet I am using: // Routes const routes = [ { path: &apos ...

Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup: <div id="mydiv">?</div> When validating a form submission in my code, I check if the div text contains a question mark like this: const f ...

The jQuery .load method is having trouble loading a local HTML file within a Cocoa WebView

Having an issue with my Cocoa WebView where I'm attempting to load a local HTML file using jQuery.load(). My code snippet looks like this: $("#mydiv").load("test.html"); // The test.html file is located within the app's bundle Although no exce ...

Exploring the wonders of ExpressJS session variables

Having transitioned from a PHP background to focusing on JS, I find myself adjusting to the differences in handling session variables. In PHP, the $_SESSION global variable was very convenient as it allowed easy access to session data throughout the code. ...

How to use Javascript to fetch HTML content from an external website

Is it possible to access and retrieve scores from for a specific week using AJAX or JSON technology? Each game on the website seems to have a unique class which could make retrieving score information easier. Any guidance or assistance would be greatly ap ...

Is it possible to modify the default behavior of a sensitive region within a button?

I created a calculator application in React and overall, it's working fine, however... I've noticed that when I hold a click longer, it only registers as a click if the mouse was pressed down and released on the button itself. Although I unders ...

Can someone help me figure out how to increase the values of two specific attributes within a class?

Currently facing a challenge with adjusting the number of likes and comments using increment for properties 'numberOfLikes' and 'comments'. Unsure whether to utilize a for loop or just the increment operator. Still new to coding, so apo ...

I just obtained the height measurement of a dynamic table - now I must transfer this height value to a different element

Recently, I encountered a situation where I needed to get the height of a dynamic table using code like this: var table = document.getElementById("test"); document.write(table.offsetHeight); However, the challenge arose when I realized that I also needed ...

Tips for transferring data between iframes on separate pages

I am currently working on implementing a web calendar module within an iframe on page-b. This module consists of 1 page with two sections. Upon entering zipcodes and house numbers, the inputs are hidden and the calendar is displayed. The technology used he ...

How to extract the values of the parent for a specific child within an array of nested JSON objects?

Take a look at this snapshot of my JSON data. const info = [{ "employees": [ { "employee": [ { "name": "Jon", "surname": "Smith&quo ...

Obtain the parameter value from the resolve function in ui-router

Using window.open, I plan to open a URL such as https://localhost:3000/new?HostId=8Ocs_Onuv1wowozxAAAS&_host_Info=excel%7Cweb%7C16.00%7Cen-us%7Cc8b501ce-c51d-b862-701e-5c623e1a70e0%7CisDialog. The site https://localhost:3000 hosts a MEAN stack applica ...