[英]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.