如何通过tsc命令行选项为输出模块指定名称而非默认index
Absolutely! You can totally customize the module-related names when compiling with tsc via command-line options—let's break down the two common scenarios you might be dealing with:
1. Changing the Output File Name (instead of default "index")
If you're referring to the filename of the compiled output (e.g., you're getting index.js by default and want a custom name), use the --outFile flag to explicitly set your desired filename. This works great for bundling multiple TypeScript files into a single output file:
tsc src/**/*.ts --outFile dist/my-custom-module.js
If you're compiling individual files and want to preserve their names but output to a specific directory, combine --rootDir and --outDir to maintain your source structure instead of getting a generic index.js:
tsc src/**/*.ts --rootDir src --outDir dist
This will mirror your src folder structure in the dist folder, so src/utils.ts becomes dist/utils.ts instead of defaulting to index.js.
2. Setting a Custom Global Module Name (for UMD/IIFE formats)
If your issue is that the global variable name for your UMD/IIFE module defaults to "index", use the --moduleName flag to define a custom name. This is super useful when your module needs to be accessible in the browser's global scope:
tsc src/main.ts --module UMD --outFile dist/my-custom-module.js --moduleName MyAwesomeModule
When you load this compiled file in a browser, your module will be available as window.MyAwesomeModule instead of the default window.index.
Just a quick note: If you prefer using a tsconfig.json file instead of typing long command lines every time, you can add these settings under the compilerOptions section (e.g., "outFile": "dist/my-custom-module.js", "moduleName": "MyAwesomeModule").
内容的提问来源于stack exchange,提问作者user7898461

