Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds the ability to generate a project using ES2015 template #176

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ This generator can also be further configured with the following command line fl
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
--es2015 use ES2015 standards
--es5 use ES5 standards
-h, --help output usage information

## License
Expand Down
22 changes: 15 additions & 7 deletions bin/express-cli.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env node

var detect = require('feature-detect-es6')
var ejs = require('ejs')
var fs = require('fs')
var minimatch = require('minimatch')
Expand Down Expand Up @@ -58,8 +59,15 @@ program
.option('-c, --css <engine>', 'add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)')
.option(' --git', 'add .gitignore')
.option('-f, --force', 'force on non-empty directory')
.option(' --es2015', 'use ES2015 standards')
.option(' --es5', 'use ES5 standards')
.parse(process.argv)

var esVersion = program.es5 ? 'es5'
: program.es2015 ? 'es2015'
: detect.all('arrowFunction', 'let') ? 'es2015'
: 'es5'

if (!exit.exited) {
main()
}
Expand Down Expand Up @@ -121,10 +129,10 @@ function copyTemplate (from, to) {

function copyTemplateMulti (fromDir, toDir, nameGlob) {
fs.readdirSync(path.join(TEMPLATE_DIR, fromDir))
.filter(minimatch.filter(nameGlob, { matchBase: true }))
.forEach(function (name) {
copyTemplate(path.join(fromDir, name), path.join(toDir, name))
})
.filter(minimatch.filter(nameGlob, { matchBase: true }))
.forEach(function (name) {
copyTemplate(path.join(fromDir, name), path.join(toDir, name))
})
}

/**
Expand All @@ -138,8 +146,8 @@ function createApplication (name, dir) {
console.log()

// JavaScript
var app = loadTemplate('js/app.js')
var www = loadTemplate('js/www')
var app = loadTemplate('js/' + esVersion + '/app.js')
var www = loadTemplate('js/' + esVersion + '/www')

// App name
www.locals.name = name
Expand Down Expand Up @@ -178,7 +186,7 @@ function createApplication (name, dir) {

// copy route templates
mkdir(dir, 'routes')
copyTemplateMulti('js/routes', dir + '/routes', '*.js')
copyTemplateMulti('js/' + esVersion + '/routes', dir + '/routes', '*.js')

// copy view templates
mkdir(dir, 'views')
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"dependencies": {
"commander": "2.11.0",
"ejs": "2.5.7",
"feature-detect-es6": "1.3.1",
"minimatch": "3.0.4",
"mkdirp": "0.5.1",
"sorted-object": "2.0.1"
Expand Down
54 changes: 54 additions & 0 deletions templates/js/es2015/app.js.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
<% Object.keys(modules).forEach(function (variable) { -%>
const <%- variable %> = require('<%- modules[variable] %>');
<% }); -%>

const index = require('./routes/index');
const users = require('./routes/users');

const app = express();

// view engine setup
<% if (view.render) { -%>
app.engine('<%- view.engine %>', <%- view.render %>);
<% } -%>
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', '<%- view.engine %>');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
<% uses.forEach(function (use) { -%>
app.use(<%- use %>);
<% }); -%>
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handler
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;
9 changes: 9 additions & 0 deletions templates/js/es2015/routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const express = require('express');
const router = express.Router();

/* GET home page. */
router.get('/', (req, res, next) => {
res.render('index', { title: 'Express' });
});

module.exports = router;
9 changes: 9 additions & 0 deletions templates/js/es2015/routes/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const express = require('express');
const router = express.Router();

/* GET users listing. */
router.get('/', (req, res, next) => {
res.send('respond with a resource');
});

module.exports = router;
90 changes: 90 additions & 0 deletions templates/js/es2015/www.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env node

/**
* Module dependencies.
*/

const app = require('../app');
const debug = require('debug')('<%- name %>:server');
const http = require('http');

/**
* Get port from environment and store in Express.
*/

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

const server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
const port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

const bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
const addr = server.address();
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
122 changes: 122 additions & 0 deletions test/cmd.js
Original file line number Diff line number Diff line change
Expand Up @@ -1014,6 +1014,128 @@ describe('express(1)', function () {
})
})
})

describe('es2015', function () {
Copy link
Author

@bluzi bluzi Jan 16, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@imcodingideas / @dougwilson, if you want to help:
The only issue I know about, is that the --es2015 flag test also runs in older Node environments in the CI.
Because older versions doesn't support es2015, the test fails when it tries to run the generated application, that obviously contains es2015 code. (as it was generated with --es2015 flag)

We should either:

  • Test es2015 support even when the --es2015 flag is presented, and show error message when a user tries to generate es2015 application on an environment where es2015 is not supported.
  • "Disable" this test if it runs on older Node versions, where es2015 is not supported.

If you'd like to help, feel free to discuss it and clear out what exactly should be done to solve this (@dougwilson), or just go ahead and implement it yourselves.
That said, I might jump in and just do it myself if I'll find the time :)

Thanks!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK. I like the test es2015 support when you use the flag. I'm just seeing these messages. I've had a long month.

var ctx = setupTestEnvironment(this.fullTitle())

it('should create basic app with vash templates', function (done) {
run(ctx.dir, ['--es2015'], function (err, stdout) {
if (err) return done(err)
ctx.files = utils.parseCreatedFiles(stdout, ctx.dir)
assert.equal(ctx.files.length, 16)
done()
})
})

it('should have "const" instead of "var" in every JavaScript file', function () {
['bin/www', 'routes/index.js', 'routes/users.js'].forEach(function (fileName) {
var filePath = path.resolve(ctx.dir, fileName)
var contents = fs.readFileSync(filePath, 'utf8')

assert.equal(contents.indexOf('var'), -1)
assert.notEqual(contents.indexOf('const'), -1)
})
})

it('should have basic files', function () {
assert.notEqual(ctx.files.indexOf('bin/www'), -1)
assert.notEqual(ctx.files.indexOf('app.js'), -1)
assert.notEqual(ctx.files.indexOf('package.json'), -1)
})

it('should have installable dependencies', function (done) {
this.timeout(30000)
npmInstall(ctx.dir, done)
})

describe('npm start', function () {
before('start app', function () {
this.app = new AppRunner(ctx.dir)
})

after('stop app', function (done) {
this.app.stop(done)
})

it('should start app', function (done) {
this.timeout(5000)
this.app.start(done)
})

it('should respond to HTTP request', function (done) {
request(this.app)
.get('/')
.expect(200, /<title>Express<\/title>/, done)
})

it('should generate a 404', function (done) {
request(this.app)
.get('/does_not_exist')
.expect(404, /<h1>Not Found<\/h1>/, done)
})
})
})

describe('es5', function () {
var ctx = setupTestEnvironment(this.fullTitle())

it('should create basic app with vash templates', function (done) {
run(ctx.dir, ['--es5'], function (err, stdout) {
if (err) return done(err)
ctx.files = utils.parseCreatedFiles(stdout, ctx.dir)
assert.equal(ctx.files.length, 16)
done()
})
})

it('should have "var" and should not have "const" in every JavaScript file', function () {
['bin/www', 'routes/index.js', 'routes/users.js'].forEach(function (fileName) {
var filePath = path.resolve(ctx.dir, fileName)
var contents = fs.readFileSync(filePath, 'utf8')

assert.notEqual(contents.indexOf('var'), -1)
assert.equal(contents.indexOf('const'), -1)
})
})

it('should have basic files', function () {
assert.notEqual(ctx.files.indexOf('bin/www'), -1)
assert.notEqual(ctx.files.indexOf('app.js'), -1)
assert.notEqual(ctx.files.indexOf('package.json'), -1)
})

it('should have installable dependencies', function (done) {
this.timeout(30000)
npmInstall(ctx.dir, done)
})

describe('npm start', function () {
before('start app', function () {
this.app = new AppRunner(ctx.dir)
})

after('stop app', function (done) {
this.app.stop(done)
})

it('should start app', function (done) {
this.timeout(5000)
this.app.start(done)
})

it('should respond to HTTP request', function (done) {
request(this.app)
.get('/')
.expect(200, /<title>Express<\/title>/, done)
})

it('should generate a 404', function (done) {
request(this.app)
.get('/does_not_exist')
.expect(404, /<h1>Not Found<\/h1>/, done)
})
})
})
})
})

Expand Down