Javascript 使用 ES6 (Babel) 导出类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29353728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:15:06  来源:igfitidea点击:

Exporting a class with ES6 (Babel)

javascriptgruntjsbrowserifyecmascript-6babeljs

提问by David Gomes

I'm writing some frontend code with ECMAScript 6 (transpiled with BabelJS, and then browserified with Browserify) so that I can have a class in one file, export it and import it in another file.

我正在使用 ECMAScript 6 编写一些前端代码(使用 BabelJS 进行转换,然后使用 Browserify 进行浏览器化),以便我可以在一个文件中创建一个类,将其导出并导入到另一个文件中。

The way I'm doing this is:

我这样做的方式是:

export class Game {
    constructor(settings) {

    ...

    }
}

And then on the file that imports the class I do:

然后在导入我做的类的文件上:

import {Game} from "../../lib/pentagine_browserified.js";
var myGame = new Game(settings);

I then compile it with grunt, this is my Gruntfile:

然后我用 编译它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"]);
};

However, on the new Game(call, I get the following error:

但是,在new Game(通话中,我收到以下错误:

Uncaught TypeError: undefined is not a function

As so, what I did was analyse the generated code by Babel and Browserify and I found this line on PlayState_browserified.js:

因此,我所做的是分析 Babel 和 Browserify 生成的代码,我在以下位置找到了这一行PlayState_browserified.js

var Game = require("../../lib/pentagine_browserified.js").Game;

I decided to print the requireoutput:

我决定打印require输出:

console.log(require("../../lib/pentagine_browserified.js"));

And it is nothing but an empty object. I decided to check out the pentagine_browserified.jsfile:

它只不过是一个空的对象。我决定查看pentagine_browserified.js文件:

var Game = exports.Game = (function () {

It seems like it is correctly exporting the class, but for some other reason it is not being required on the other file.

似乎它正确导出了类,但由于其他原因,其他文件不需要它。

Also, I'm sure the file is being required properly because changing the string "../../lib/pentagine_browserified.js"spits out a Not Founderror, so it is going for the right file, that I'm sure about.

此外,我确信该文件是正确需要的,因为更改字符串会"../../lib/pentagine_browserified.js"产生Not Found错误,所以它会用于正确的文件,我确信这一点。

采纳答案by X?pplI'-I0llwlg'I -

Browserify is meant to be fed a single "entry point" file, through which it recursively traverses all of your requirestatements, importing the code from other modules. So you should be require'ing the _babel.jsversions of modules, not _browserified.jsones.

Browserify 旨在提供单个“入口点”文件,通过该文件它递归遍历您的所有require语句,从其他模块导入代码。所以你应该使用模块require_babel.js版本,而不是模块的版本_browserified.js

From the looks of it, you intend for your app's "entry point" to be demos/helicopter_game/PlayState_browserified.js, yeah? If that's the case:

从它的外观来看,您打算将您的应用程序的“入口点”设为demos/helicopter_game/PlayState_browserified.js,是吗?如果是这种情况:

  • In PlayState.js, change it to import {Game} from "../../lib/pentagine_babel.js";.
  • In Gruntfile.js, remove "lib/pentagine_browserified.js": "lib/pentagine_babel.js".
  • 在 PlayState.js 中,将其更改为import {Game} from "../../lib/pentagine_babel.js";.
  • 在 Gruntfile.js 中,删除"lib/pentagine_browserified.js": "lib/pentagine_babel.js".

Works for me. Let me know if that suffices or I am misunderstanding your requirements here.

为我工作。让我知道这是否足够,否则我在这里误解了您的要求。

P.S. You can use babelifyto avoid having separate Grunt tasks for Babel and Browserify. See my answer herefor an example.

PS 您可以使用babelify来避免为 Babel 和 Browserify 设置单独的 Grunt 任务。见我的答案在这里的一个例子。

回答by Stefan Musarra

I had a slightly different file configuration, that gave me some difficulty to get the "require" syntax to work in Node, but this post gave me the hint on how to used the babel-ified version of the file name.

我有一个稍微不同的文件配置,这给我在 Node 中使用“require”语法带来了一些困难,但是这篇文章给了我关于如何使用文件名的 babel-ified 版本的提示。

I am using WebStorm with the FileWatcher option set to Babel, and I have the FileWatcher configured to watch all files with suffix .jsx, and rename the compiled output file from {my_file}.jsx to {my_file}-compiled.js.

我正在使用 WebStorm,并将 FileWatcher 选项设置为 Babel,并且我将 FileWatcher 配置为监视所有后缀为 .jsx 的文件,并将编译后的输出文件从 {my_file}.jsx 重命名为 {my_file}-compiled.js。

So in my test case, I have 2 files:

所以在我的测试用例中,我有 2 个文件:

Person.jsx:

人.jsx:

class Person { ... }

export { Person as default}

and another file that wants to import it:

和另一个想要导入它的文件:

Test.jsx:

测试.jsx:

var Person = require('./Person-compiled.js');

I couldn't get the "require" statement to find the module until I started the file path with './' and also add '-compiled.js' to properly specify the file name so that Node es5 could find the module.

直到我用“./”开始文件路径并添加“-compiled.js”以正确指定文件名以便Node es5可以找到模块之前,我无法获得“require”语句来查找模块。

I was also able to use the "import" syntax:

我还可以使用“导入”语法:

import Person from './Person-compiled.js';

Since I have set up my WebStorm project as a Node ES5 project, I have to run 'Test-compiled.js' (not 'Test.jsx').

由于我已将 WebStorm 项目设置为 Node ES5 项目,因此我必须运行“Test-compiled.js”(而不是“Test.jsx”)。