简体   繁体   中英

Trying to export a class as a module ES6 babel

I have an ES6 class which I am trying to export as a module, however I am getting an error

class Car {
    constructor(make) { 
        this.make = make;
        this.currentSpeed = 25;
    }

    printCurrentSpeed(){
          console.log(this.make + ' is going ' + this.currentSpeed + ' mph.');
    }
}

module.exports = Car;

I am trying to use the Car module like this

var Car = require("./models/Car");

let must = new Car('Mustang');
console.log(must.printCurrentSpeed());

I am using browserify with babelify to transform to ES6

browserify -t babelify main.js -o public/scripts/bundle.js",

Am I exporting the Car module correctly, or am I doing something wrong?

Would requiring babel/register solve your problem?

require('babel/register');

As stated here: https://babeljs.io/docs/usage/require/

All subsequent files required by node with the extensions .es6, .es, .jsx and .js will be transformed by Babel. The polyfill is also automatically required.

My issue is that I was working on an isomorphic React.js app and the babelify browserify transform was fine, and my bundle.js file was being transpiled fine. It was an issue with the server side portion of my script, as this wasn't being compiled to ES6 with babel.

I am hoping this doesn't mean I need duplicate copies of my ES6 and ES5 in my source files, as this is what I was trying to avoid, and with the browserify babelify transform I was able to code in ES6 and just point to the main.js file.

This was my example react server repository I was basing this on, I was basically using node-jsx to transparently require() jsx from within node, so I will just need a way to do this with babel.

require('node-jsx').install(); 
var express = require('express');
var React = require('react');
var APP = require('./app'); // the JSX app with calls to ES6 modules
var app = express();
var port = 3000;
var ip = '127.0.0.1';

app.get('/', function(req, res) {
  var markup = React.renderToString(APP());
  res.send(markup);
});

I think similar to this question I can use either babel-node or use node with --harmony flag to run script with es6 features 我认为类似于这个问题我可以使用babel-node或使用带有--harmony标志的节点来运行带有es6功能的脚本

The answer to this was that I can use either babel-node or use node with --harmony flag to run the script with es6 features.

Here are some example alt/iso Isomorphic React Examples using babel-node server which demonstrate this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM