Webpack generates asynchronous downloadable, shared, and cached shared code

I am creating a multi-page application and I am using webpack to bind my client javascript.

I have the following:

webpack.config.js

module.exports = {
  entry: {
    page1: [
      '@babel/polyfill',
      'whatwg-fetch',
      './src/scripts/page1.js'
    ],
    page2: [
      '@babel/polyfill',
      'whatwg-fetch',
      './src/scripts/page2.js'
    ]
  },
  output: {
    filename: './dist/scripts/[name].js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.join(__dirname, 'src', 'scripts'),
        use: {loader: 'babel-loader'}
      }
    ]
  }
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      filename: 'common'
    })
  ]
}

page1.html

<!DOCTYPE html>
<html>
  <head>
  </head>

  <body>
    <!-- some code -->

    <script src="/dist/common.js"></script>
    <script src="/dist/page1.js"></script>
  </body>
</html>

page1.js

import Typed from 'typed'//<- node_modules import
import myLib from './mylib.js'//<- local lib import

// some code

And page2.html and page2.js as such ...

It works great


I would like to optimize the loading time and choose the async loading strategy for my scripts, but also keep the shared code separate , so as to take as much advantage of browser caching as possible.

I would ideally want to set up CommonsChunkPluginto be able to do this:

<!DOCTYPE html>
<html>
  <head>
    <!-- old plain synchronous load -->
    <script src="/dist/minimalWebpackSorcellery.js"></script>

    <!-- async load -->
    <script async src="/dist/page1.js"></script>
  </head>

  <body>
    <!-- some code -->
  </body>
</html>

... with the plugin do the following:

  • webpack- , ( <script>)
  • , -, @babel/polyfill, require d , typed node_module ./myLib.js ( async <script async>)
  • ( webPackJsonp )

?

?

async, children ,

+4

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


All Articles