Uncaught SyntaxError: Cannot use import statement outside a module, when using '@babel/preset-env'

Viewed 145

I need to use @babel/preset-env to correct the issues with js functions in ie11. But when babel adds necessary modules in particular js files like (import('module_path')) browsers don't understand them. I'm using gulp and webpack to config the project. I've read that I need to config my webpack for using imports in browser, but I don't know how to do that.

Here is my webpack part in my project:

webpack({
        entry: entry, // some custom libs are added here
        output: {
            path: 'general/lib',
            filename: "[name].min.js",
        },
        externals: {
            "underscore": "_"
        },
        resolveLoader: {
            modulesDirectories: ["node_modules", "node_modules_local"],
        },
        module: {
            loaders: getLoadersList(args)
        },
        plugins: getPluginsList(args)
    }, function(error, stats){

        var warnings = stats.compilation.warnings;
        var errors = stats.compilation.errors;

        if (errors.length) cb(errors[0].toString())
        // else if (warnings.length) cb(warnings[0].toString())
        else cb();
    });

function getLoadersList(opts) {

    var loaders = [
        {
            test: /\.js$/,
            include: opts.uni ? [] : getIgnoreList(),
            loader: 'dummy'
        }
    ];

    if (!opts.no_filter) {
        loaders.push({
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
                presets: ["@babel/preset-env"],
                plugins: ["@babel/plugin-transform-runtime"]
            }
        });
    };

    return loaders;
};

function getPluginsList(opts) {
    var plugins = [
        new OnlyIfChangedPlugin({
            cacheDirectory: path.join('tmp/webpack_cache'),
            cacheIdentifier: 'app_modules'
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "app-module-common",
            minChunks: 2
        })
    ];

    if (!opts.debug && !opts.no_filter) {
        plugins.push(new webpack.optimize.UglifyJsPlugin({
            mangle: false
        }));
    };

    return plugins;
};

And here is my babel config in gulp:

var pipeline = gulp.src(files, opts);
pipeline = pipeline.pipe(babel({
presets: [ [
        "@babel/preset-env",
        {
            modules: false,
            corejs:2,
            useBuiltIns:"usage", 
        }
      ] ],
    plugins: []
}));
0 Answers
Related