简单搭建 ES6 的运行环境

使用 Webstrom 搭建一个运行环境,通过手动编译的方式实现 ES6 向 ES5 的转码。

若是需要了解 Webstrom 中自己实现 ES6 转码环境的搭建,请参考如下文章:
webstrom 配置 es6 的运行环境

整体目录结构如下:
简单搭建 ES6 的运行环境_第1张图片
node_modules 目录是存放下载的 library 的,在使用 npm 时会自动添加这个目录

out 是转码后的文件输出目录(先放一个空的)

src 存放 ES6 的代码

下面是一个 ES6 代码的例子:

//readMyFile.js
const a = {
    name: "name"
};
console.log(`${a.name}`);

const init = Symbol("init");
class ReadMyFile {
    constructor(file) {
        this.file = file;
    }

    //私有方法
    [init]() {
        console.log("init....");
    }

    read() {
        this[init]();

        //read file....

    }
}
export default ReadMyFile;

直接运行这个代码是会报错的,需要通过 babel 进行转译成 ES5 方可运行。

如下是 package.json 文件的配置:

{
  "name": "ES6",
  "version": "0.0.1",
  "scripts": {
    "compile": "babel src --out-dir out --preset es2015"
  },
  "dependencies": {
    "babel-cli": "~6.26.0",
    "babel-preset-es2015": "~6.24.1"
  }
}

右击 package.json 文件中,scripts 节点下的 compile,在弹出的菜单页面选择 Run compile
简单搭建 ES6 的运行环境_第2张图片

下面的输出框中会有如下输出:
简单搭建 ES6 的运行环境_第3张图片

若是 exit code 为 0 则表示成功了。

然后就可以在 out 目录下面去查看编译后的 js 文件了 。

//readMyFile.js
"use strict";

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var a = {
    name: "name"
};
console.log("" + a.name);

var init = Symbol("init");

var ReadMyFile = function () {
    function ReadMyFile(file) {
        _classCallCheck(this, ReadMyFile);

        this.file = file;
    }

    //私有方法


    _createClass(ReadMyFile, [{
        key: init,
        value: function value() {
            console.log("init....");
        }
    }, {
        key: "read",
        value: function read() {
            this[init]();

            //read file....
        }
    }]);

    return ReadMyFile;
}();

exports.default = ReadMyFile;

这个文件就可以直接运行了。

右键点击这个文件,选择 Run readMyFile.js

下面的输出区域没有报错就表明成功了。

你可能感兴趣的:(es6)