kshetline
kshetline

Reputation: 13734

How do I compile TypeScript code into a single .js file, executable via "node mycode.js"?

I'd like to be able to do this without webpack, gulp, etc, just "tsc [args] mycode.ts". Is that even possible?

In my package.json, I have a build command like this:

    "build:mycode": "tsc --allowSyntheticDefaultImports --lib es2018 --lib dom -m amd -t es2018 --moduleResolution node --outFile ./mycode.js ./mycode.ts",

(The reason all of the above config is done with tsc command line arguments, instead of being set up in tsconfig.json, is that I'm generating a build script that's apart from my main project, which does use tsconfig.json, webpack, etc.)

I tried to use -m commonjs, but that's not allowed with --outFile, only amd or system.

The problem is that the code generated this way produces this error when invoked by node:

ReferenceError: define is not defined

I can't figure out how to define define. Is there an argument to the node command that will supply the necessary definition? Everything I've googled so far invokes extra tools I'd rather avoid if possible, or is targeted at a web browser rather than creating a command-line tool.

Note: Any solution which involves a <scr ipt> tag is NOT applicable.

Upvotes: 0

Views: 721

Answers (2)

Damian Akpan
Damian Akpan

Reputation: 84

Here's a simple script that I made. It should work well for your use case

#!/bin/sh

SRCDIR=src
OUTDIR=build
pre_clean(){
    if [ -f build/index.js ];
    then
        rm build/index.js
    fi
}

pre_clean
mkdir -p tmp
mkdir -p $OUTDIR


tsc $SRCDIR/*.ts --outDir tmp

cd tmp

for file in *.js
do
    echo "// $file " >> ../$OUTDIR/index.js
    echo "" >> ../$OUTDIR/index.js
    cat $file >> ../$OUTDIR/index.js
    # sed 1,2d $file >> ../$OUTDIR/index.js
    echo "" >> ../$OUTDIR/index.js
done

# Cleanup
cd ..
rm -r tmp

# Add package.json
sed s:build/index.js:index.js:g package.json > build/package.json
cp package-lock.json build

true

Upvotes: 0

jsejcksn
jsejcksn

Reputation: 33931

It is not possible to concatenate CommonJS modules to a single file using tsc's --outFile parameter. See https://github.com/microsoft/TypeScript/issues/7252 for a discussion.

You will need to use a bundler (e.g. webpack) in order to achieve your goal.


Original answer:

When compiling a single file using tsc, the --outFile argument is not needed. Also, the --lib option accepts either one arg, or a (comma-separated) list. Here's a modified version of your example:

tsc \
  --allowSyntheticDefaultImports \
  --lib es2018,dom \
  --module commonjs \
  --target es2018 \
  --moduleResolution node \
  ./script.ts

This will not bundle your script, but merely transpile it to JavaScript. It will still rely on any external imports.

Upvotes: 1

Related Questions