Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack with Babel lazy load module using ES6 recommended Import() approach not working

I'm trying to do code splitting and lazy loading with webpack using the import() method

import('./myLazyModule').then(function(module) {
    // do something with module.myLazyModule
}

I'm getting

'import' and 'export' may only appear at the top level

Note top level imports are working fine, i'm just getting an issue when I try and using the dynamic variant of import()

var path = require('path');

module.exports = {
    entry: {
        main: "./src/app/app.module.js",
    },
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "[name]-application.js"
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: [{
                    loader: 'babel-loader',
                    query: {
                        presets: ['es2015']
                    }
                }]
            }
        ]
    },
    resolve : {
        modules : [
            'node_modules',
            'bower_components'
        ]
    },
    devtool : "source-map"
}

EDIT:

If I change it so the syntax reads, it works.... but the chunk comments don't work to label the bundle. I'm confused because the documentation says the the following is depreciated.

The use of System.import in webpack did not fit the proposed spec, so it was deprecated in webpack 2.1.0-beta.28 in favor of import().

System.import('./myLazyModule').then(function(module) {
    // do something with module.myLazyModule
}
like image 741
Mantisimo Avatar asked Jul 25 '17 15:07

Mantisimo


People also ask

Does webpack support ES6?

It's extremely confusing because webpack itself DOES support ES6 module syntax! But in webpack. config you still have to use require . It seems overkill to install babel JUST for the webpack config file!

Can not Resolve babel-loader?

To solve the error "Module not found: Error: Can't resolve 'babel-loader'", make sure to install the babel-loader package by opening your terminal in your project's root directory and running the command npm install -D babel-loader and restart your development server.


1 Answers

You need the plugin syntax-dynamic-import to be able to use the import() function with Babel.

Install it with:

npm install --save-dev @babel/plugin-syntax-dynamic-import

And add it to your plugins:

{
    presets: ['es2015'],
    plugins: ['@babel/plugin-syntax-dynamic-import']
}
like image 65
Michael Jungo Avatar answered Oct 22 '22 13:10

Michael Jungo