When you have server-side code in TypeScript, it cannot be run directly by default, you have several options.
-
ts-node -O '{"module": "commonjs"}' src/index.ts
orts-node-dev -O '{"module": "commonjs"}' src/index.ts
-
nodemon
with registerts-node
-
tsc
thenode dist/index.js
I believe, it is best to tsc
first, as ts-node
isn't meant for production.
Also, if you use Babel, or some special JavaScript features, you will need build steps, anyway (with @babel/cli
).
Now, if you have multiple TypeScript folders, not just src/
, like tests/
, it becomes complex to use tsc
(you need multiple tsconfig.json
). What would you do? Use a bundler? Which one?
My current option is using Webpack with webpack-node-externals with the following settings.
// webpack.config.js
const path = require('path')
const nodeExternals = require('webpack-node-externals')
module.exports = {
mode: 'production',
devtool: false,
optimization: {
minimize: false
},
entry: './src/index.ts',
output: {
filename: 'index.js',
path: path.resolve(process.env.OUT_DIR || 'dist')
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader'
}
]
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json']
},
target: 'node',
externals: [
nodeExternals()
]
}
Tried Babel and Rollup, but it failed with emitDecoratorMetadata
and reflect-metadata
. I cannot use Typegoose, nor liteorm.
Top comments (1)
At work, we do transpile it to good old node-js javascript for portability (cloud) reasons mainly.
Using NestJS you kind of get this out of the box though with their compiler cli