[英]Babel 'protoToAssign' transformer and ES6 class inheritance
[英]Exporting a class with ES6 (Babel)
我正在用ECMAScript 6编写一些前端代码(用BabelJS编译,然后用Browserify进行浏览),这样我就可以在一个文件中创建一个类,将其导出并导入到另一个文件中。
我这样做的方式是:
export class Game {
constructor(settings) {
...
}
}
然后在导入我的类的文件上:
import {Game} from "../../lib/pentagine_browserified.js";
var myGame = new Game(settings);
然后我用grunt
编译它,这是我的Gruntfile
:
module.exports = function(grunt) {
"use strict";
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('grunt-browserify');
grunt.initConfig({
"babel": {
options: {
sourceMap: false
},
dist: {
files: {
"lib/pentagine_babel.js": "lib/pentagine.js",
"demos/helicopter_game/PlayState_babel.js": "demos/helicopter_game/PlayState.js"
}
}
},
"browserify": {
dist: {
files: {
"lib/pentagine_browserified.js": "lib/pentagine_babel.js",
"demos/helicopter_game/PlayState_browserified.js": "demos/helicopter_game/PlayState_babel.js"
}
}
}
});
grunt.registerTask("default", ["babel", "browserify"]);
};
但是,在new Game(
通话,我得到以下错误:
Uncaught TypeError: undefined is not a function
因此,我所做的是通过Babel和Browserify分析生成的代码,我在PlayState_browserified.js
上找到了这一行:
var Game = require("../../lib/pentagine_browserified.js").Game;
我决定打印require
输出:
console.log(require("../../lib/pentagine_browserified.js"));
它只不过是一个空洞的物体。 我决定查看pentagine_browserified.js
文件:
var Game = exports.Game = (function () {
看起来它正确地导出了类,但由于其他原因,在其他文件中不需要它。
此外,我确定该文件是正确的,因为更改字符串"../../lib/pentagine_browserified.js"
发出一个Not Found
错误,所以它会Not Found
正确的文件,我确定关于。
Browserify旨在提供单个“入口点”文件,通过该文件递归遍历所有require
语句,从其他模块导入代码。 所以你应该require
_babel.js
版本的模块,而不是_browserified.js
。
从它的外观来看,你打算让你的应用程序的“入口点”为demos/helicopter_game/PlayState_browserified.js
,是吗? 如果是这样的话:
import {Game} from "../../lib/pentagine_babel.js";
。 "lib/pentagine_browserified.js": "lib/pentagine_babel.js"
。 适合我。 如果这样就足够了,或者我在这里误解了您的要求,请告诉我。
PS你可以使用babelify来避免为Babel和Browserify分别执行Grunt任务。 见我的答案在这里的一个例子。
我有一个稍微不同的文件配置,这让我在Node中使用“require”语法有些困难,但这篇文章给了我关于如何使用文件名的babel-ified版本的提示。
我使用WebStorm并将FileWatcher选项设置为Babel,并且我将FileWatcher配置为监视所有带后缀.jsx的文件,并将编译后的输出文件从{my_file} .jsx重命名为{my_file} -compiled.js。
所以在我的测试用例中,我有2个文件:
Person.jsx:
class Person { ... }
export { Person as default}
和另一个想要导入它的文件:
Test.jsx:
var Person = require('./Person-compiled.js');
在用'./'启动文件路径之前,我无法获取“require”语句来查找模块,并添加'-compiled.js'以正确指定文件名,以便Node es5可以找到模块。
我还能够使用“import”语法:
import Person from './Person-compiled.js';
由于我已将我的WebStorm项目设置为Node ES5项目,因此我必须运行'Test-compiled.js'(而不是'Test.jsx')。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.