问题
I have an ES6 class which I am trying to export as a module, however I am getting an error SyntaxError: Unexpected reserved word
Car.js
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
main.js
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?
回答1:
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.
回答2:
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);
});
Update: I think similar to this question I can use either babel-node or use node with --harmony flag to run script with es6 features
回答3:
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.
来源:https://stackoverflow.com/questions/29337966/trying-to-export-a-class-as-a-module-es6-babel