代码分离-import() webpack2.x 中文文档 翻译

代码分离-使用import()

中文文档地址点击这里

动态导入

目前,类函模import()块加载的语法建议——syntax proposal整体交给ECMAScript。
ES2015(es6)加载器说明定义import()作为一个方法用来动在运行时态加载es6模块。
在webpack中的import()是个分离点——split-point,用来把被请求的模块独立成一个单独的模块。import()吧模块的名字作为一个参数,并且返回一个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配合

如果你想使用babel时使用import,你需要使用syntax-dynamic-import插件(babel的插件,卸载.babelrc中),然而该差价仍停留在Stage3(第三阶段),会出现编译错误。如果建议到了说明推广阶段,那么这个标准见不被采用(指ECMAScript标准演进)。

npm install --save-dev babel-core babel-loader babel-plugin-syntax-dynamic-import babel-preset-es2015
# 如下示例,加载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',
        //如果有这个设置则不用在添加.babelrc
        options: {
          presets: [['es2015', {modules: false}]],
          plugins: ['syntax-dynamic-import']
        }
      }]
    }]
  }
};

注意
使用syntax-dynamic-import插件时,如下情况将报错。

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

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

配合babel, async/await

使用ES2017 async/await 配合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 替代 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()

例子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值