代碼分離-import() webpack2.x 中文文檔 翻譯

代碼分離-使用import()

中文文檔地址點擊這裏node

動態導入

目前,類函模import()塊加載的語法建議——syntax proposal總體交給ECMAScript。
ES2015(es6)加載器說明定義import()做爲一個方法用來動在運行時態加載es6模塊。
在webpack中的import()是個分離點——split-point,用來把被請求的模塊獨立成一個單獨的模塊。import()吧模塊的名字做爲一個參數,而且返回一個Promise: import(name)->Promise.webpack

index.jsgit

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

determineDate();

babel配合

若是你想使用babel時使用import,你須要使用syntax-dynamic-import插件(babel的插件,卸載.babelrc中),然而該差價仍停留在Stage3(第三階段),會出現編譯錯誤。若是建議到了說明推廣階段,那麼這個標準見不被採用(指ECMAScript標準演進)。es6

npm install --save-dev babel-core babel-loader babel-plugin-syntax-dynamic-import babel-preset-es2015
# 以下示例,加載moment
npm install --save moment

index-es2015.jsgithub

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.jsweb

module.exports = {
  entry: './index-es2015.js',
  output: {
    filename: 'dist.js',
  },
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /(node_modules)/,
      use: [{
        loader: 'babel-loader',
        //若是有這個設置則不用在添加.babelrc
        options: {
          presets: [['es2015', {modules: false}]],
          plugins: ['syntax-dynamic-import']
        }
      }]
    }]
  }
};

注意
使用syntax-dynamic-import插件時,以下狀況將報錯。npm

  • Module build failed: SyntaxError: 'import' and 'export' may only appear at the top level, or (import 和 export只能在最外層,也就是不能用在函數或者塊中)promise

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

配合babel, async/await

使用ES2017 async/await 配合import():app

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 替代 require.ensure?

好的方面:使用import()可以在加載模塊失敗時進行錯誤處理,由於返回的是個Promise(基於promise)。

警告:require.ensure能夠使用參數給模塊命名,然而import目前上不具有改功能,若是你須要保留該功能很重要,能夠繼續使用require.ensure

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

System.import被替代

由於在webpack中使用System.import已經不合建議規範,所以將在webpack版本v2.1.0-beta.28中啓用。建議使用import()

例子

相關文章
相關標籤/搜索