Search code examples
webpackbabeljsecmascript-6

what`s the best way to make babel6 support Array.from in webpack?


I'm using a webpack config below:

    var path = require('path');
var webpack = require('webpack');

module.exports = {
    plugins: [
        new webpack.ProvidePlugin({
            'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
        })
    ],
    entry: {
        demo1 : ['babel-polyfill', './src/js/page/demo1.js']
    },

    output: {
        path: 'dist/js/page',
        filename: '[name].js'
    },
    devtool: 'eval-source-map',
    module: {
        loaders: [
            {
                test: /\.js$/,
                include: [
                    path.resolve(__dirname, "src")
                ],
                exclude: path.resolve(__dirname, "node_modules"),
                loader: "babel-loader",
                query: {
                    plugins: ['transform-runtime'],
                    presets: ['es2015', 'react']
                }
            },
            { test: /\.scss$/, loader: 'style!css!sass?sourceMap'}
        ]
    },
    resolve: {
        root: path.resolve(__dirname, "src"),
        extensions: ['', '.js', '.json', '.scss']
    }
};

As it shows, I merge the whole babel-polyfill module to the entry file demo1.js to support Array.from. But I don`t think it`s a good idea to do this cuz it will heavier the entry file too much.

So is here any loader/plugin/preset that I could use to support Array.from in webpack as what babel-polyfill does?


Solution

  • You will want to integrate with core-js directly then, which is what Babel uses under the hood. Then, you can cherry-pick features you want to provide compatibility for by explicitly requiring individual modules.

    require('core-js/fn/array/from');
    
    // Then, from within any module:
    Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3]
    

    This is what Babel 6 will effectively set up for you through presets.