Utilize Webpack to integrate core-js polyfills into your project

To ensure the bundle includes es6 polyfills for methods like Object.assign and Array.prototype.filter, I am using core-js. If these methods are not natively supported, they will be backed by core-js.

I have created a sample application highlighting this issue which can be found in this gist: https://gist.github.com/tiberiucorbu/fb9acd2f286e3452ef06df9d6bae9210

Dealing with polyfills in webpack has been challenging. Different approaches have been attempted but none have worked as expected:

Using the provider plugin

Inspiration :

Attempt :

webpack.config.js

    new webpack.ProvidePlugin({
        '': 'imports?this=>window!core-js/index.js'
    })

Result :

No change observed. The test still fails as before.

Defining core-js files in the webpacks entry config:

Attempt :

entry: {
    'app': [
        'core-js',
        './index.ts'
    ]
},

Result : The core-js files are included in the bundle but do not execute properly. Test continues to fail.

How can I make sure that the bundle contains the polyfills and executes them correctly in this (webpack, karma, typescript) setup?


Update : Finding a Solution

Another approach was taken involving importing polyfills and running them separately from webpack/typescript imports. This workaround may seem unconventional but it works.

Changes made from the initial version posted:

@@ -3,8 +3,10 @@ var webpack = require('webpack');
 module.exports = {
     entry: {
         'app': [
-            'core-js',
             './index.ts'
+        ],
+        'polyfills': [
+            'core-js'
         ]
     },
     output: {
@@ -30,4 +32,4 @@ module.exports = {
         //   '': 'imports?this=>window!core-js/index.js'
         // })
     ]
-};
\ No newline at end of file
+};

A new file was created to import core-js as name and execute it:

import * as polyfills from 'core-js';

polyfills();

The bundle along with the test files were then imported in the karma configuration:

@@ -4,6 +4,7 @@ module.exports = function (config) {
     config.set({
         frameworks: ['jasmine'],
         files: [
+            './dist/polyfills.js',
             './**/*.spec.ts'

         ],
@@ -26,4 +27,4 @@ module.exports = function (config) {
         concurrency: Infinity,
         plugins: ['karma-phantomjs-launcher', 'karma-sourcemap-loader', 'karma-webpack', 'karma-jasmine']
     })
-};
\ No newline at end of file
+};

The test now passes successfully:

26 01 2017 01:30:40.594:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
26 01 2017 01:30:40.596:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
26 01 2017 01:30:40.613:INFO [launcher]: Starting browser PhantomJS
26 01 2017 01:30:41.081:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket /#c9shUPdbgFg0XwJbAAAA with id 77560741
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 SUCCESS (0.04 secs / 0.002 secs)

The Gist is now functioning correctly with the mentioned changes:

https://gist.github.com/tiberiucorbu/fb9acd2f286e3452ef06df9d6bae9210

If there is a more elegant solution without an intermediate file, that would be great to know. For now, this method gets the job done.

Answer №1

One way to ensure ES6 compatibility in webpack is by using babel:

Update your webpack.config.js file with the following configuration:

module.exports = {
    ...
    module: { 
       loaders: [
          { 
              test: /\.jsx?$/, 
              loader: 'babel-loader', 
              exclude: /node_modules/, 
              query: { 
                 presets: ['es2015'] 
              }
          }
       ]
    }
} 

To install babel loader, run the following command:

npm install babel-loader babel-core babel-preset-es2015 webpack --save-dev

By using babel, you can take full advantage of ES6 features like arrow functions and import statements without needing any polyfills.

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

Converting an object into an array using React and TypeScript

Extracted from a form is an object with input, output, and outputType fields that can vary between number, string, and boolean types. To display the information in a table without the output type, I have created a mapped obj. However, I also need to prese ...

In Angular 17, is there a way to trigger a component's method when a Signal is modified?

Our component is designed to monitor signals from a Service: export class PaginationComponent { private readonly pageSize = this.listService.pageSize.asReadonly(); private readonly totalCount = this.listService.totalCount.asReadonly(); readonly pag ...

Apply a different background color to ion-item when it is clicked

Is there a way to change the background color of an ion-item when it is clicked by a user? Any help on how to achieve this would be greatly appreciated. Here's an example code snippet: <ion-item (click)="openDetail(variant)">{{variant.Product ...

What is the best way to set up Storybook with Vue Cli 3?

I'm facing difficulties installing Storybook in a Vue Cli 3 project. Every time I try to npm run storybook, I encounter this error: Cannot find module '@storybook/vue/dist/server/config/defaults/webpack.config.js' I suspect that this i ...

Issue: Module "expose?Zone!zone.js" could not be located

Just started experimenting with Angular 2 and encountering an issue when importing zone.js as a global variable: https://i.stack.imgur.com/gUFGn.png List of my packages along with their versions: "dependencies": { "angular2": "2.0.0-beta.3", "es ...

Angular does not recognize "modal" as a valid element in this context

After successfully creating a component for my project using Angular, I encountered an issue when adding a modal window. Now, nothing appears when serving my app and Angular throws the error "modal is not a known element". HTML Document <modal> < ...

Leverage a single React micro-frontend within another React micro-frontend by incorporating webpack

In the structure of my web application with multiple micro-frontends (MFE) apps, it is simplified as follows: MFE-Projects |------Packages | |---------Auth | | |------dist | | |------webpack.config.js | |---------Common ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

Can a type be designed to allow the second argument to be typed according to the type of the first argument?

In my preference, I would rather have the type of the second argument inferred from the type of the first argument instead of being explicitly specified as a type argument. This way, it can be passed without the need for explicit typing. I typically defin ...

Testing for target instanceof window.Window in jest involves writing a test case using the expect keyword

I am currently working on a function in TypeScript that handles scrolling. Here is the code snippet with type definitions for reference... function scroll(target: HTMLElement, {posX, posY}: ScrollPosition): void { if (target instanceof window.Window) ...

If the parameter type is "never", the ReturnType will be "any"

short tale const xyz = (a:never):number=>1 type b = ReturnType< typeof xyz> //any const xyz2 = (a:number, b:never):number=>1 type b2 = ReturnType< typeof xyz2> //any playground If any parameter type is never, the ReturnType becom ...

Obtaining data from a TypeScript decorator

export class UploadGreetingController { constructor( private greetingFacade: GreetingFacade, ) {} @UseInterceptors(FileInterceptor('file', { storage: diskStorage({ destination: (req: any, file, cb) => { if (process.env ...

Tips for validating and retrieving data from a radio button paired with an input box in reactjs

I'm diving into the world of React and facing a challenge with multiple radio buttons that have associated input fields, like in this image: https://i.stack.imgur.com/Upy3T.png Here's what I need: If a user checks a radio button with a ...

Tips on reordering Angular material tabs on the fly

I am working with a group of 7 tabs using Angular material: <mat-tab-group #tabGroup [selectedIndex]="selectedIndex"> <mat-tab label="Tab 1">Content 1</mat-tab> <mat-tab label="Tab 2">Content 2</mat-tab> <mat-t ...

exploration of unique npm packages with vue-loader in development

After configuring my project with vue-loader, I included several postcss plugins in the designated config file. Now, I aim to integrate the GSAP package (downloaded from npm). Where should I insert the code for webpack to recognize it? ...

Enum-centric type guard

Could I create a custom type guard to verify if a specified string is part of a specific string enum in a more specialized way? Check out the following example: enum MyEnum { Option1 = 'option one', Option2 = 'option two', } const ...

The interface remains static even after the property has been modified

There is a function in my codebase called getData() that fetches data from an API. I am trying to call this function from a different component, which I will refer to as MainComponent and AnotherComponent for the sake of clarity: import MainComponent from ...

Passing data from child components to parent components in NextJs using Typescript

I have created a new component <ConnectWallet setConnected={(t: boolean) => console.log(t)}> <>test</> </ConnectWallet> The component is initialized as follows import { useState, useEffect } from ' ...

Creating a dynamic union return type in Typescript based on input parameters

Here is a function that I've been working on: function findFirstValid(...values: any) { for (let value of values) { if (!!value) { return value; } } return undefined; } This function aims to retrieve the first ...

Guide on creating a generic type that depends on the arguments provided, specifically a union type

I am dealing with the following similar types: class ActionFoo { action: 'foo'; foo: string; } class ActionBar { action: 'bar'; bar: number; } In addition, I have some handler functions for each type of defined "action", such a ...