美文网首页
2017/05/09

2017/05/09

作者: 风吹过的空气 | 来源:发表于2017-05-09 16:25 被阅读17次

今天要记录的是如何使用babel将es6和es7转化为es5,使用yarn而不是npm,因为yarn的速度更快,下面进行手写记录

前提确保全局安装了webpack
  • yarn init,生成一个package.json文件
  • yarn add babel-core babel-preset-es2015 babel-preset-stage-0 babel-loader,其中babel-prest-es2015是针对es6转化为es5,而babel-preset-stage-0是针对es7转化为es5,
  • touch index.js

function timeout(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function asyncPrint(value, ms) {
await timeout(ms);
console.log(value);
}
asyncPrint('hello world', 50);
```
上面代码的意思是在控制台中50毫秒之后打印出hello world

  • touch webpack.config.js
module.exports = {
  entry: 'index.js',
  output: {
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: ['babel-loader?presets[]=es2015&presets[]=stage-0']
    }]
   }
};
  • $ webpack
    然后就生成了一个文件bundle.js,在里面能看到转译之后的es5代码
"use strict";


var asyncPrint = function () {
  var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(value, ms) {
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return timeout(ms);

          case 2:
            console.log(value);

          case 3:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, this);
  }));

  return function asyncPrint(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function timeout(ms) {
  return new Promise(function (resolve) {
    setTimeout(resolve, ms);
  });
}

asyncPrint('hello world', 50);

相关文章

网友评论

      本文标题:2017/05/09

      本文链接:https://www.haomeiwen.com/subject/difitxtx.html