Emit does not preserve empty lines
Hi,
TS Version: 1.1
Given
function foo() {
var x = 10;
var y = 11;
}
We used to get
function foo() {
var x = 10;
var y = 11;
}
In the new compiler the line break is missing
function foo() {
var x = 10;
var y = 11;
}
(Both compilers removed the first empty line, but the new compiler has gone a step further.)
This can affect the experience when debugging JavaScript in the browser.
The crowd wants preserveWhitespace: true/false
@ORESoftware ++
Reason this is important is that TypeScript is supposed to "degrade gracefully" to JS. Right now it can't preserve new lines making the JS a bit dense to read, especially if you write TypeScript, but you are supposed to deliver JS to some place else.
+1 preserveWhitespace: true/false
Temporary hack
Use esformatter to add linebreaks.
With the following configuration file:
{
"lineBreak": {
"before": {
"FunctionDeclaration": ">=2",
"FunctionDeclarationOpeningBrace": 0,
"FunctionDeclarationClosingBrace": 1,
"MethodDefinition": ">=2",
"ClassDeclaration": ">=2"
},
"after": {
"FunctionDeclaration": ">=2",
"FunctionDeclarationOpeningBrace": 1,
"MethodDefinitionClosingBrace": ">=2",
"ClassClosingBrace": ">=2"
}
}
}
@mtraynham Your example:
(<any> x).a('#test')
.b('test')
.c(() => 'foo')
.d(() => 'bar')
.e(() => 5)
.f(() => 6);
with the latest compiler produces this JS:
x.a('#test')
.b('test')
.c(function () { return 'foo'; })
.d(function () { return 'bar'; })
.e(function () { return 5; })
.f(function () { return 6; });
(see TS PlayGround https://goo.gl/JViurr )
A lot has changed since TS Version 1.1 (the version of TypeScript for which this issue was created). Maybe this issue can be closed? @ahejlsberg ?
@valera-rozuvan I had opened #2259 instead. My issue was related to line feeds, but not the exact same issue described by this bug. #2259 was closed a while back (May 2015).
This is the bril-andrew esformatter configuration but with a bug fixed, (when the class declaration contained the word import there was no line break):
{
"lineBreak": {
"before": {
"FunctionDeclaration": ">=2",
"FunctionDeclarationOpeningBrace": 0,
"FunctionDeclarationClosingBrace": 1,
"MethodDefinition": ">=2",
"ClassDeclaration": ">=2",
"ExportNamedDeclaration": 2
},
"after": {
"FunctionDeclaration": ">=2",
"FunctionDeclarationOpeningBrace": 1,
"MethodDefinitionClosingBrace": ">=2",
"ClassClosingBrace": ">=2"
}
}
}
I don't think using esformatter solves the whole problem. Sure, it can automatically insert blank lines around functions etc. But for me, blank lines within functions are even more crucial. We use blank lines like paragraphs in prose: to group individual thoughts.
Those blank lines within functions help to communicate the structure of the function. Without them, I find that readability suffers.
@ahejlsberg I am seeing incorrect line numbers in my unit testing output when using ts-jest, and this issue seems to be caused by the empty lines being removed in the js output. I am curious why it is so difficult to leaves these lines in the final js. Is there any more information out there on this? Can we help somehow to make this happen? :)
Or has it been merged already and not released yet? --> V4 Next Big Version #3143
@JimTheMan If you use source maps then maybe the source-map-support package can help you get the correct stack traces in the output.
I also run into this issue. I came up with a workaround by creating a diff patch and revert whitespace changes in the patch. jsdiff allows you to create a structured patch object and manipulate it as you wish.
import * as diff from 'diff';
const patch =
diff.parsePatch(diff.createPatch('file', oldText, newText, '', ''));
const hunks = patch[0].hunks;
for (let i = 0; i < hunks.length; ++i) {
let lineOffset = 0;
const hunk = hunks[i];
hunk.lines = hunk.lines.map(line => {
if (line === '-') {
lineOffset++;
return ' ';
}
return line;
});
hunk.newLines += lineOffset;
for (let j = i + 1; j < hunks.length; ++j) {
hunks[j].newStart += lineOffset;
}
}
return diff.applyPatch(oldText, patch);
With this workaround, you can preserve all the line breaks from the original file.
@zeroliu Does it introduce a noticeable time delay in compile step?
@ahejlsberg Do you think it's worth fixing this issue?
@valera-rozuvan depending on the size of your project. For my use cases where I transpile 10-ish files of 100-1000 LOC, it doesn't introduce any noticeable delay.
Any solutions here yet? I run in this trouble too...
I was part way into trying to fix this in the compiler itself when my teammate @emadum reminded me that tsc can preserve comments. Here's a little gulp pipeline that seems to do a fairly decent job of preserving newlines:
const gulp = require('gulp');
const ts = require('gulp-typescript');
const through = require('through2');
function preserveNewlines() {
return through.obj(function(file, encoding, callback) {
const data = file.contents.toString('utf8');
const fixedUp = data.replace(/\n\n/g, '\n/** THIS_IS_A_NEWLINE **/');
file.contents = Buffer.from(fixedUp, 'utf8');
callback(null, file);
});
}
function restoreNewlines() {
return through.obj(function(file, encoding, callback) {
const data = file.contents.toString('utf8');
const fixedUp = data.replace(/\/\*\* THIS_IS_A_NEWLINE \*\*\//g, '\n');
file.contents = Buffer.from(fixedUp, 'utf8');
callback(null, file);
});
}
gulp.task('default', function () {
return gulp.src('src/**/*.ts')
.pipe(preserveNewlines())
.pipe(ts({
removeComments: false
}))
.pipe(restoreNewlines())
.pipe(gulp.dest('lib'));
});
I think a more clever comment would prevent some false positives, but it seems to work well for us today. I've only tested this on a relatively small file, but the performance overhead there was minimal.
hth
@mbroadst
I ended up using your idea as a base, and eventually expanded upon it until it became an npm module: https://www.npmjs.com/package/gulp-preserve-typescript-whitespace
I credited your post in the Readme, hopefully you don't mind :)
Is this still being considered? I see this experiment: https://github.com/microsoft/TypeScript/pull/37814 and https://github.com/microsoft/TypeScript/pull/42303, but don't know if there is any plan to deliver it some day.
Is there a way I could contribute to fixing this? If I could get some guidance around what an acceptable fix might look like, I'd be willing to take a stab at it.
@CarabusX I took slightly minimalistic approach, but very similar to yours:
function preserveWhitespace(content) {
return content.replace(/(\s)/g, (m) => {
return `/**_P${m.charCodeAt(0)}**/`;
});
}
function restoreWhitespace(content) {
return content.replace(/\/\*\*_P(\d+)\*\*\//g, (_, m) => {
return String.fromCharCode(m);
});
}
content = preserveWhitespace(content);
const output = ts.transpileModule(content, {
reportDiagnostics: false,
compilerOptions: {
target: ts.ScriptTarget.ESNext,
importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Preserve,
sourceMap: true,
removeComments: false,
},
});
output.outputText = restoreWhitespace(output.outputText.replace(/\s+/g, ''));
however it doesn't work well with imports
I tried many suggestions from this thread but none worked for me. After a while, however, I managed to come up with my own solution.
Before I share the code, I should note that this code relies on Prettier for formatting to get the JS code consistent with the TS code. I already use Prettier in all my projects, so I just copied the config I am using anyway.
One final note, as my use case for this was the Docusaurus website for https://github.com/sapphiredev, I have also decided to publish this conversion and formatting as an NPM package: https://www.npmjs.com/package/@sapphire/docusaurus-plugin-ts2esm2cjs
Now on to the code. This transpiles TS into ESM and then further converts that ESM into CJS.
const { runTransform } = require('esm-to-cjs');
const ts = require('typescript');
const prettier = require('prettier');
const sapphirePrettierConfig = require('@sapphire/prettier-config');
const documentationPrettierConfig = {
...sapphirePrettierConfig,
tabWidth: 2,
useTabs: false,
printWidth: 120,
parser: 'babel'
};
/** @type {import('ts').CompilerOptions} */
const tsCompilerOptions = {
module: ts.ModuleKind.ESNext,
newLine: ts.NewLineKind.LineFeed,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
target: ts.ScriptTarget.ESNext,
removeComments: false,
esModuleInterop: true,
pretty: true
};
/**
* Transpiles input TypeScript code to ESM code.
* @param {string} code The code to transpile
* @returns {{ outputText: string; diagnostics: unknown[]; sourceMapText?: string }} Input code transpiled to ESM
*/
const tsToEsm = (code) => ts.transpileModule(code, { reportDiagnostics: false, compilerOptions: tsCompilerOptions });
/**
* Transforms input ESM code to CJS code.
* @param {string} code The code to transform
* @returns Input code transformed to CommonJS
*/
const esmToCjs = (code) => runTransform(code, { quote: 'single' });
/**
* Escaped new lines in code with block comments so they can be restored by {@link restoreNewLines}
* @param {string} code The code to escape new lines in
* @returns The same code but with new lines escaped using block comments
*/
const escapeNewLines = (code) => code.replace(/\n\n/g, '\n/* :newline: */');
/**
* Reverses {@link escapeNewLines} and restores new lines
* @param {string} code The code with escaped new lines
* @returns The same code with new lines restored
*/
const restoreNewLines = (code) => code.replace(/\/\* :newline: \*\//g, '\n');
/**
* Formats the code using Prettier
* @param {string} code The code to prettier format
* @returns Prettier formatted code
*/
const prettierFormatCode = (code) => prettier.format(code, documentationPrettierConfig).slice(0, -1);
/**
* The example code that we'll be transpiling and formatting.
* Of note here is that it also has a type only import that will be removed during transpilation,
* and it needs to be accounted for with the restoration of new lines.
*/
const codeStr = `import { Command, Args } from '@sapphire/framework';
import type { Message } from 'discord.js';
export class EchoCommand extends Command {
public constructor(context: Command.Context, options: Command.Options) {
super(context, {
...options,
aliases: ['parrot', 'copy'],
description: 'Replies with the text you provide'
});
}
public async messageRun(message: Message, args: Args) {
// ...
}
}`;
const emptyLineEscapedTsCode = escapeNewLines(codeStr);
const esmCode = tsToEsm(emptyLineEscapedTsCode).outputText;
const cjsCode = esmToCjs(esmCode);