Webpack with Babel lazy load module using ES6 it is recommended to use the Import () method does not work

I am 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 get

'import' and 'export' can only be displayed at the top level

Note that top-level imports work fine, I just get the problem when I try to use the dynamic option 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 that the syntax reads, it works ... but the chunk comments do not work to label the package. I am confused because the documentation says that the following is depreciating.

Using System.import in webpack did not meet the proposed specification, 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
}
+4
1

syntax-dynamic-import, import() Babel.

:

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

:

{
    presets: ['es2015'],
    plugins: ['syntax-dynamic-import']
}
+6

Source: https://habr.com/ru/post/1682235/


All Articles