粘贴图片

简介

为了能够在开发环境下使用更高标准的 ECMA 语法来进行开发,而又需要适配当前执行环境,babel 在其中充当脚本编译工作,将开发脚本翻译成生产脚本。

安装

以下文字以 babel@7 为准。

首先需要下载以下模块到开发依赖中:

npm install -D @babel/core @babel/preset-env @babel/polyfill @babel/cli

配置

在项目根目录新建 babel.config.js

'use strict';

module.exports = {
    presets: ['@bebel/env'],

    plugins: []
};

注意第 4 行,表示使用 @babel/preset-env 提供的预设环境,兼容当前已经发布为标准规范的 es 版本(比如 2019 年底之前已经发布的 es2017、es2018),不包括提案内的语法。

使用

编译

在 src 目录下新建 loader.js

'use strict';

export async function getImageSize(url) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => {
            resolve({ width: img.originWidth, height: img.originHeight });
        };
        img.onerror = () => reject;
        img.src = url;
    });
}

在 src 下新建 index.js:

'use strict';

import { getImageSize } from './loader';

document.onreadystatechange = async () => {
    const url = 'https://example.com/image.png';
    let size;

    try {
        size = await getImageSize(url);
    } catch (err) {
        return alert(`image load error: ${err.message}`);
    }

    alert(`image size is: width = ${size.width}, height = ${size.height}`);
};

从上面代码可以看到,我们在开发代码中使用到了 es6(Promise、模板字符串)、es7(await、async),使用 babel 可以将上述代码翻译成 es5 语法的代码。命令行执行:

npx babel src -d dist

执行之后的,从打印的日子中可以看到,我们的工程没有直接引用 core-js@2 这个模块,而上文提到的那些 runtime 模块就是 core-js@2 模块内的,会在 dist 目录下生成 index.js

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getImageSize = getImageSize;

function getImageSize(url) {
  return regeneratorRuntime.async(function getImageSize$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          return _context.abrupt("return", new Promise(function (resolve, reject) {
            var img = new Image();

            img.onload = function () {
              resolve({
                width: img.originWidth,
                height: img.originHeight
              });
            };

            img.onerror = function () {
              return reject;
            };

            img.src = url;
          }));

        case 1:
        case "end":
          return _context.stop();
      }
    }
  });
}

(function _callee() {
  var url, size;
  return regeneratorRuntime.async(function _callee$(_context2) {
    while (1) {
      switch (_context2.prev = _context2.next) {
        case 0:
          url = 'https://example.com/image.png';
          _context2.prev = 1;
          _context2.next = 4;
          return regeneratorRuntime.awrap(getImageSize(url));

        case 4:
          size = _context2.sent;
          _context2.next = 10;
          break;

        case 7:
          _context2.prev = 7;
          _context2.t0 = _context2["catch"](1);
          return _context2.abrupt("return", alert("image load error: ".concat(_context2.t0.message)));

        case 10:
          alert("image size is: width = ".concat(size.width, ", height = ").concat(size.height));

        case 11:
        case "end":
          return _context2.stop();
      }
    }
  }, null, null, [[1, 7]]);
})();

可以看到编译后的代码的可读性比较差,但从其中的第 9 行可以看到,有新增了一个 regeneratorRuntime 全局对象。这些 runtime 代码是 babel 的垫片依赖,默认这些垫片是不会在代码中直接引用的,可以在配置中配置直接引用。

垫片

修改

在项目根目录新建 babel.config.js

'use strict';

module.exports = {
    presets: [
        '@bebel/env',
        {
            useBuiltIns: 'usage'
        }
    ],

    plugins: []
};

重新执行:

npx babel src -d dist

WARNING: We noticed you're using the `useBuiltIns` option without declaring a core-js version. Currently, we assume version 2.x when no version is passed. Since this default version will likely change in future versions of Babel, we recommend explicitly setting the core-js version you are using via the `corejs` option.

You should also be sure that the version you pass to the `corejs` option matches the version specified in your `package.json`'s `dependencies` section. If it doesn't, you need to run one of the following commands:

  npm install --save core-js@2    npm install --save core-js@3
  yarn add core-js@2              yarn add core-js@3

Successfully compiled 2 files with Babel.

可以看到,在 dist 目录下生成了两个脚本文件:loader.js 和 index.js

loader.js:

'use strict';

require("core-js/modules/es6.object.define-property");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getImageSize = getImageSize;

require("core-js/modules/es6.promise");

require("core-js/modules/es6.object.to-string");

require("regenerator-runtime/runtime");

function getImageSize(url) {
  return regeneratorRuntime.async(function getImageSize$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          return _context.abrupt("return", new Promise(function (resolve, reject) {
            var img = new Image();

            img.onload = function () {
              resolve({
                width: img.originWidth,
                height: img.originHeight
              });
            };

            img.onerror = function () {
              return reject;
            };

            img.src = url;
          }));

        case 1:
        case "end":
          return _context.stop();
      }
    }
  });
}

index.js:

'use strict';

require("regenerator-runtime/runtime");

var _loader = require("./loader");

document.onreadystatechange = function _callee() {
  var url, size;
  return regeneratorRuntime.async(function _callee$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          url = 'https://example.com/image.png';
          _context.prev = 1;
          _context.next = 4;
          return regeneratorRuntime.awrap((0, _loader.getImageSize)(url));

        case 4:
          size = _context.sent;
          _context.next = 10;
          break;

        case 7:
          _context.prev = 7;
          _context.t0 = _context["catch"](1);
          return _context.abrupt("return", alert("image load error: ".concat(_context.t0.message)));

        case 10:
          alert("image size is: width = ".concat(size.width, ", height = ").concat(size.height));

        case 11:
        case "end":
          return _context.stop();
      }
    }
  }, null, null, [[1, 7]]);
};
0 条评论
作者
状态
标签
二维码
目录