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.