Webpack-encore: Lazyloading an import

Created on 15 Feb 2018  路  4Comments  路  Source: symfony/webpack-encore

Hi,

I need (for webperfs) to import a module only if a condition is met.
In the webpack doc there is an example :

button.onclick = e => import(/* webpackChunkName: "print" */ './print').then(module => {
    var print = module.default;

    print();
});

But when I run encore :

Syntax Error: Unexpected token (28:26)

  26 |     //     test();
  27 |     // };
> 28 |     button.onclick = e => import(/* webpackChunkName: "global-vars" */ './global-vars').then(module => {
     |                           ^
  29 |         var test = module.default;
  30 |
  31 |         test();

Maybe I'm missing something, or it is not supported by webpack-encore ?

Most helpful comment

Hey @zek0faws!

Of course Encore supports this - we support anything Webpack has ;). But, this is poorly documented on Webpack. Using import() as a function is not "yet" legal ES code. So, you need to tell Babel to "allow this code. We talk about this issue in Webpack in general on KnpU: https://knpuniversity.com/screencast/javascript-webpack/code-splitting#the-dynamic-import-proposal

The solution should be to:

1) Run yarn add babel-plugin-syntax-dynamic-import --dev
2) Then configure babel to use this:

# webpack.config.js
# ...

.configureBabel(function(babelConfig) {
    babelConfig.plugins.push('syntax-dynamic-import');
});

Let me know if that works!

All 4 comments

Hey @zek0faws!

Of course Encore supports this - we support anything Webpack has ;). But, this is poorly documented on Webpack. Using import() as a function is not "yet" legal ES code. So, you need to tell Babel to "allow this code. We talk about this issue in Webpack in general on KnpU: https://knpuniversity.com/screencast/javascript-webpack/code-splitting#the-dynamic-import-proposal

The solution should be to:

1) Run yarn add babel-plugin-syntax-dynamic-import --dev
2) Then configure babel to use this:

# webpack.config.js
# ...

.configureBabel(function(babelConfig) {
    babelConfig.plugins.push('syntax-dynamic-import');
});

Let me know if that works!

Yes it's working like a charm.
Thank you @weaverryan !

For information, this trick will create another .js file in the build directory, which will be called when the condition is met.

Maybe it would be nice to add it to the docs ? I mean the encore docs.
There are no examples of Lazy Loading.

Indeed, I think we should - it鈥檚 complex :)

205 is related

Was this page helpful?
0 / 5 - 0 ratings