我正在使用 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
output:
console.log(require("../../lib/pentagine_browserified.js"));
它只不过是一个空物体。我决定查看一下pentagine_browserified.js
file:
var Game = exports.Game = (function () {
看起来它正确导出了该类,但由于某些其他原因,其他文件不需要它。
另外,我确信该文件是正确需要的,因为更改了字符串"../../lib/pentagine_browserified.js"
吐出一个Not Found
错误,所以我确信它会寻找正确的文件。