Code Separation - import() webpack2.x Chinese Document Translation

Keywords: Javascript Webpack npm github ECMAScript

Code separation - using import()

Chinese Document Address click here

Dynamic import

Currently, class module import() block loaded Syntax Recommendation The whole is handed over to ECMAScript.
ES2015(es6) loader description Define import() as a method to load the es6 module at runtime.
import() in webpack is a split-point, used to separate the requested module into a separate module. import() takes the name of the module as a parameter and returns a Promise: import (name) - > Promise.

index.js

function determineDate() {
  import('moment').then(function(moment) {
    console.log(moment().format());
  }).catch(function(err) {
    console.log('Failed to load moment', err);
  });
}

determineDate();

babel coordination

If you want to use import when you use babel, you need to use the syntax-dynamic-import plug-in (babel plug-in, uninstall. babelrc), but the difference is still in Stage 3 (phase 3), and there will be compilation errors. If the recommendation reaches the explanatory promotion stage, then this standard is not adopted (referring to the evolution of ECMAScript standard).

npm install --save-dev babel-core babel-loader babel-plugin-syntax-dynamic-import babel-preset-es2015
# For the following example, load moment
npm install --save moment

index-es2015.js

function determineDate() {
  import('moment')
    .then(moment => moment().format('LLLL'))
    .then(str => console.log(str))
    .catch(err => console.log('Failed to load moment', err));
}

determineDate();

webpack.config.js

module.exports = {
  entry: './index-es2015.js',
  output: {
    filename: 'dist.js',
  },
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /(node_modules)/,
      use: [{
        loader: 'babel-loader',
        //If you have this setting, you don't need to add. babelrc
        options: {
          presets: [['es2015', {modules: false}]],
          plugins: ['syntax-dynamic-import']
        }
      }]
    }]
  }
};

Be careful
When using the syntax-dynamic-import plug-in, errors will be reported as follows.

  • Module build failed: SyntaxError: 'import' and 'export' may only appear at the top level, or (import and export It can only be used at the outermost level, that is, it can't be used in functions or blocks.)

  • Module build failed: SyntaxError: Unexpected token, expected {

Cooperate with babel, async/await

Use ES2017 async/await to cooperate with import():

npm install --save-dev babel-plugin-transform-async-to-generator babel-plugin-transform-regenerator babel-plugin-transform-runtime

index-es2017.js

async function determineDate() {
  const moment = await import('moment');
  return moment().format('LLLL');
}

determineDate().then(str => console.log(str));

webpack.config.js

module.exports = {
  entry: './index-es2017.js',
  output: {
    filename: 'dist.js',
  },
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /(node_modules)/,
      use: [{
        loader: 'babel-loader',
        options: {
          presets: [['es2015', {modules: false}]],
          plugins: [
            'syntax-dynamic-import',
            'transform-async-to-generator',
            'transform-regenerator',
            'transform-runtime'
          ]
        }
      }]
    }]
  }
};

import instead of require.ensure?

On the plus side: Using import() enables error handling when the loading module fails, because the return is a Promise (promise-based).

Warning: Request. ensure can use parameters to name modules, but import currently does not have a change function. If you need to retain this function is important, you can continue to use require.ensure.

require.ensure([], function(require) {
  var foo = require("./module");
}, "custom-chunk-name");

System.import is replaced

Because the use of System.import in webpack is no longer recommended, it will be enabled in webpack version v2.1.0-beta.28. import() is recommended.

Example

Posted by joix on Tue, 16 Jul 2019 15:55:07 -0700