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 3 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
58 changes: 33 additions & 25 deletions bin/express-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ var program = require('commander')
var readline = require('readline')
var sortedObject = require('sorted-object')
var util = require('util')
var detect = require('feature-detect-es6')
Copy link
Contributor

Choose a reason for hiding this comment

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

This should be alphabetized


var MODE_0666 = parseInt('0666', 8)
var MODE_0755 = parseInt('0755', 8)
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 All @@ -68,7 +76,7 @@ if (!exit.exited) {
* Install an around function; AOP.
*/

function around (obj, method, fn) {
Copy link
Contributor

Choose a reason for hiding this comment

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

There are a lot of changes like this that don't seem related to yiur changes. In fact deleting the space is a linting error

function around(obj, method, fn) {
var old = obj[method]

obj[method] = function () {
Expand All @@ -82,7 +90,7 @@ function around (obj, method, fn) {
* Install a before function; AOP.
*/

function before (obj, method, fn) {
function before(obj, method, fn) {
var old = obj[method]

obj[method] = function () {
Expand All @@ -95,7 +103,7 @@ function before (obj, method, fn) {
* Prompt for confirmation on STDOUT/STDIN
*/

function confirm (msg, callback) {
function confirm(msg, callback) {
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
Expand All @@ -111,20 +119,20 @@ function confirm (msg, callback) {
* Copy file from template directory.
*/

function copyTemplate (from, to) {
function copyTemplate(from, to) {
write(to, fs.readFileSync(path.join(TEMPLATE_DIR, from), 'utf-8'))
}

/**
* Copy multiple files from template directory.
*/

function copyTemplateMulti (fromDir, toDir, nameGlob) {
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 @@ -134,12 +142,12 @@ function copyTemplateMulti (fromDir, toDir, nameGlob) {
* @param {string} dir
*/

function createApplication (name, dir) {
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 Expand Up @@ -347,7 +355,7 @@ function createApplication (name, dir) {
* @param {String} pathName
*/

function createAppName (pathName) {
function createAppName(pathName) {
return path.basename(pathName)
.replace(/[^A-Za-z0-9.()!~*'-]+/g, '-')
.replace(/^[-_.]+|-+$/g, '')
Expand All @@ -361,7 +369,7 @@ function createAppName (pathName) {
* @param {Function} fn
*/

function emptyDirectory (path, fn) {
function emptyDirectory(path, fn) {
fs.readdir(path, function (err, files) {
if (err && err.code !== 'ENOENT') throw err
fn(!files || !files.length)
Expand All @@ -372,11 +380,11 @@ function emptyDirectory (path, fn) {
* Graceful exit for async STDIO
*/

function exit (code) {
function exit(code) {
// flush output for Node.js Windows pipe bug
// https://github.com/joyent/node/issues/6247 is just one bug example
// https://github.com/visionmedia/mocha/issues/333 has a good discussion
function done () {
function done() {
if (!(draining--)) _exit(code)
}

Expand All @@ -398,7 +406,7 @@ function exit (code) {
* Determine if launched from cmd.exe
*/

function launchedFromCmd () {
function launchedFromCmd() {
return process.platform === 'win32' &&
process.env._ === undefined
}
Expand All @@ -407,11 +415,11 @@ function launchedFromCmd () {
* Load template file.
*/

function loadTemplate (name) {
function loadTemplate(name) {
var contents = fs.readFileSync(path.join(__dirname, '..', 'templates', (name + '.ejs')), 'utf-8')
var locals = Object.create(null)

function render () {
function render() {
return ejs.render(contents, locals)
}

Expand All @@ -425,7 +433,7 @@ function loadTemplate (name) {
* Main program.
*/

function main () {
function main() {
// Path
var destinationPath = program.args.shift() || '.'

Expand Down Expand Up @@ -472,7 +480,7 @@ function main () {
* @param {string} dir
*/

function mkdir (base, dir) {
function mkdir(base, dir) {
var loc = path.join(base, dir)

console.log(' \x1b[36mcreate\x1b[0m : ' + loc + path.sep)
Expand All @@ -486,7 +494,7 @@ function mkdir (base, dir) {
* @param {String} newName
*/

function renamedOption (originalName, newName) {
function renamedOption(originalName, newName) {
return function (val) {
warning(util.format("option `%s' has been renamed to `%s'", originalName, newName))
return val
Expand All @@ -499,7 +507,7 @@ function renamedOption (originalName, newName) {
* @param {String} message
*/

function warning (message) {
function warning(message) {
console.error()
message.split('\n').forEach(function (line) {
console.error(' warning: %s', line)
Expand All @@ -514,7 +522,7 @@ function warning (message) {
* @param {String} str
*/

function write (path, str, mode) {
function write(path, str, mode) {
fs.writeFileSync(path, str, { mode: mode || MODE_0666 })
console.log(' \x1b[36mcreate\x1b[0m : ' + path)
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"commander": "2.11.0",
"ejs": "2.5.7",
"minimatch": "3.0.4",
"feature-detect-es6": "^1.3.1",
Copy link
Contributor

Choose a reason for hiding this comment

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

Need to change to specific version instead of verion range.

Copy link
Contributor

Choose a reason for hiding this comment

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

Also alphabetize

"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.