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

Add typescript support #248

Open
wants to merge 7 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ This generator can also be further configured with the following command line fl
--no-view use static html instead of view engine
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
--typescript add TypeScript support
-f, --force force on non-empty directory
-h, --help output usage information

Expand Down
82 changes: 77 additions & 5 deletions bin/express-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ 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(' --typescript', 'add TypeScript support')
.parse(process.argv)

if (!exit.exited) {
Expand Down Expand Up @@ -150,9 +151,30 @@ function createApplication (name, dir) {
}
}

if (program.typescript) {
pkg.scripts['build'] = 'tsc'

pkg.devDependencies = {}
pkg.devDependencies['typescript'] = '~3.7.5'
pkg.devDependencies['@types/node'] = '~13.7.0'
Copy link
Contributor

Choose a reason for hiding this comment

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

Would this cause an issue when generated and used on an older node.js like, say 10.x?

Copy link
Author

Choose a reason for hiding this comment

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

It should be safe on older node environment as the version of the generated codes are controlled via tsconfig.json (line 5, "target": "es5"). Currently it is set compiling codes down to ES5 to support most of the older node.js.

Copy link
Contributor

Choose a reason for hiding this comment

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

Gotcha. I guess i mean typescript-wise. As in I assume that the node 13 types include definitions that do not apply/work on node 10, which then reduces the useful type checking that would prevent that?

Copy link
Author

Choose a reason for hiding this comment

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

Yes, you are correct.

As the typing version of node is not one-to-one, perhaps we can adjust it to match the major version of current node.

However, during testing I found that node typing below v8 causes typing mismatch errors so that I suggest setting the minimum of @types/node to v8.

// When below v8 (tested with v6.17.1):

node_modules/@types/connect/index.d.ts:21:42 - error TS2689: Cannot extend an interface 'http.IncomingMessage'. Did you mean 'implements'?

21     export class IncomingMessage extends http.IncomingMessage {
pkg.devDependencies['@types/node'] = '^' + Math.max(8, parseInt(process.version.replace('v', '')))
// example output => "@types/node": "^12"

pkg.devDependencies['@types/debug'] = '~4.1.5'
Copy link
Contributor

Choose a reason for hiding this comment

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

Should the types package version pach the debug package version?

pkg.devDependencies['@types/express'] = '~4.16.1'

pkg.dependencies['tslib'] = '~1.10.0'
Copy link
Author

Choose a reason for hiding this comment

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

As current settings automatically add the helper codes (e.g. ES6+ polyfills) into every related output files, I added tslib so that code duplication can be avoided.

}

// JavaScript
var app = loadTemplate('js/app.js')
var www = loadTemplate('js/www')
var appTemplatePath
var wwwTemplatePath
if (program.typescript) {
appTemplatePath = 'ts/app.ts'
wwwTemplatePath = 'ts/www.ts'
} else {
appTemplatePath = 'js/app.js'
wwwTemplatePath = 'js/www'
}
var app = loadTemplate(appTemplatePath)
var www = loadTemplate(wwwTemplatePath)

// App name
www.locals.name = name
Expand All @@ -167,6 +189,9 @@ function createApplication (name, dir) {
app.locals.modules.logger = 'morgan'
app.locals.uses.push("logger('dev')")
pkg.dependencies.morgan = '~1.9.1'
if (program.typescript) {
pkg.devDependencies['@types/morgan'] = '~1.7.37'
}

// Body parsers
app.locals.uses.push('express.json()')
Expand All @@ -176,6 +201,9 @@ function createApplication (name, dir) {
app.locals.modules.cookieParser = 'cookie-parser'
app.locals.uses.push('cookieParser()')
pkg.dependencies['cookie-parser'] = '~1.4.4'
if (program.typescript) {
pkg.devDependencies['@types/cookie-parser'] = '~1.4.2'
}

if (dir !== '.') {
mkdir(dir, '.')
Expand Down Expand Up @@ -206,13 +234,25 @@ function createApplication (name, dir) {
}

// copy route templates
var routeScriptsDir
var routeScriptsNameGlob
if (program.typescript) {
routeScriptsDir = 'ts/routes'
routeScriptsNameGlob = '*.ts'
} else {
routeScriptsDir = 'js/routes'
routeScriptsNameGlob = '*.js'
}
mkdir(dir, 'routes')
copyTemplateMulti('js/routes', dir + '/routes', '*.js')
copyTemplateMulti(routeScriptsDir, dir + '/routes', routeScriptsNameGlob)

if (program.view) {
// Copy view templates
mkdir(dir, 'views')
pkg.dependencies['http-errors'] = '~1.6.3'
if (program.typescript) {
pkg.devDependencies['@types/http-errors'] = '~1.6.3'
}
switch (program.view) {
case 'dust':
copyTemplateMulti('views', dir + '/views', '*.dust')
Expand Down Expand Up @@ -250,21 +290,33 @@ function createApplication (name, dir) {
app.locals.modules.compass = 'node-compass'
app.locals.uses.push("compass({ mode: 'expanded' })")
pkg.dependencies['node-compass'] = '0.2.3'
if (program.typescript) {
copyTemplate('declarations/node-compass.d.ts', path.join(dir, 'node-compass.d.ts'))
}
break
case 'less':
app.locals.modules.lessMiddleware = 'less-middleware'
app.locals.uses.push("lessMiddleware(path.join(__dirname, 'public'))")
pkg.dependencies['less-middleware'] = '~2.2.1'
if (program.typescript) {
pkg.devDependencies['@types/less-middleware'] = '~2.0.31'
}
break
case 'sass':
app.locals.modules.sassMiddleware = 'node-sass-middleware'
app.locals.uses.push("sassMiddleware({\n src: path.join(__dirname, 'public'),\n dest: path.join(__dirname, 'public'),\n indentedSyntax: true, // true = .sass and false = .scss\n sourceMap: true\n})")
pkg.dependencies['node-sass-middleware'] = '0.11.0'
if (program.typescript) {
pkg.devDependencies['@types/node-sass-middleware'] = '0.0.31'
}
break
case 'stylus':
app.locals.modules.stylus = 'stylus'
app.locals.uses.push("stylus.middleware(path.join(__dirname, 'public'))")
pkg.dependencies['stylus'] = '0.54.5'
if (program.typescript) {
pkg.devDependencies['@types/stylus'] = '0.48.32'
}
break
}

Expand Down Expand Up @@ -325,15 +377,30 @@ function createApplication (name, dir) {
if (program.git) {
copyTemplate('js/gitignore', path.join(dir, '.gitignore'))
}
if (program.typescript) {
copyTemplate('ts/tsconfig.json', path.join(dir, 'tsconfig.json'))
}

// sort dependencies like npm(1)
pkg.dependencies = sortedObject(pkg.dependencies)
if (pkg.devDependencies) {
pkg.devDependencies = sortedObject(pkg.devDependencies)
}

// write files
write(path.join(dir, 'app.js'), app.render())
var appScriptName
var wwwScriptName
if (program.typescript) {
appScriptName = 'app.ts'
wwwScriptName = 'bin/www.ts'
Copy link
Contributor

Choose a reason for hiding this comment

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

The www script shouldn't have an extension; it follows the pattern of being an executable (with shebang on the top).

Copy link
Author

Choose a reason for hiding this comment

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

Got it, may be adding a post-build script to create a symbolic link with name www, pointing to www .js?

As some people may want to generate source-maps for the compiled JS files, I afraid directly renaming it may break the file linkage.

For example,

// add postbuild.js

var fs = require('fs')
var path = require('path')

// Create a symlink, linking www to www.js
var wwwScriptPath = path.join(__dirname, 'bin/www.js')
var wwwPath = path.join(__dirname, 'bin/www')
if (fs.existsSync(wwwScriptPath) && !fs.existsSync(wwwPath)) {
  fs.symlinkSync(wwwScriptPath, wwwPath)
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Unfortunately normal users cannot create symbolic links on windows.

Copy link
Author

Choose a reason for hiding this comment

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

How about if coping www .js as www?

var fs = require('fs')
var path = require('path')

// Polyfill copyFileSync for node < 8.5.0
if (!fs.copyFileSync) {
  fs.copyFileSync = function (src, dest, flags) {
    fs.writeFileSync(dest, fs.readFileSync(src), flags)
  }
}

// Copy www.js to www
var wwwScriptPath = path.join(__dirname, 'bin/www.js')
var wwwPath = path.join(__dirname, 'bin/www')
if (fs.existsSync(wwwScriptPath)) {
  fs.copyFileSync(wwwScriptPath, wwwPath)
}

} else {
appScriptName = 'app.js'
wwwScriptName = 'bin/www'
}
write(path.join(dir, appScriptName), app.render())
write(path.join(dir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n')
mkdir(dir, 'bin')
write(path.join(dir, 'bin/www'), www.render(), MODE_0755)
write(path.join(dir, wwwScriptName), www.render(), MODE_0755)

var prompt = launchedFromCmd() ? '>' : '$'

Expand All @@ -346,6 +413,11 @@ function createApplication (name, dir) {
console.log()
console.log(' install dependencies:')
console.log(' %s npm install', prompt)
if (program.typescript) {
console.log()
console.log(' compile code:')
console.log(' %s npm run build', prompt)
}
console.log()
console.log(' run the app:')

Expand Down
51 changes: 51 additions & 0 deletions templates/ts/app.ts.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<% if (view) { -%>
import createError from 'http-errors';
<% } -%>
import express from 'express';
import * as path from 'path';
<% Object.keys(modules).sort().forEach(function (variable) { -%>
import <%- variable %> from '<%- modules[variable] %>';
<% }); -%>

<% Object.keys(localModules).sort().forEach(function (variable) { -%>
import <%- variable %> from '<%- localModules[variable] %>';
<% }); -%>

let app = express();

<% if (view) { -%>
// 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 %>');

<% } -%>
<% uses.forEach(function (use) { -%>
app.use(<%- use %>);
<% }); -%>

<% mounts.forEach(function (mount) { -%>
app.use(<%= mount.path %>, <%- mount.code %>);
<% }); -%>

<% if (view) { -%>
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});

// 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');
}) as express.ErrorRequestHandler);

<% } -%>
export default app;
4 changes: 4 additions & 0 deletions templates/ts/declarations/node-compass.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module 'node-compass' {
const compass: any;
export default compass;
}
9 changes: 9 additions & 0 deletions templates/ts/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as express from 'express';
const router = express.Router();

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

export default router;
9 changes: 9 additions & 0 deletions templates/ts/routes/users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as express from 'express';
const router = express.Router();

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

export default router;
66 changes: 66 additions & 0 deletions templates/ts/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
"importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
Loading