dsherret / code-block-writer Goto Github PK
View Code? Open in Web Editor NEWCode writer for JavaScript and TypeScript code.
License: MIT License
Code writer for JavaScript and TypeScript code.
License: MIT License
Kind of a long function name... can't think of anything shorter.
Seems like it's staying in the string even after the newline (this was obviously a mistake, but this is a bug nonetheless):
function printCommaListExpression(node: ts.CommaListExpression) {
writer.write("ts.createCommaList(").newLine();
writer.indentBlock(() => {
"[\n" + "\n " + node.elements.map(item => getNodeText(item)).join(",\n ) + "\n]"
});
writer.write(");");
}
Would be better to first check the string length before pushing it onto the internal array.
Doesn't make sense that it's withHangingIndentation
. Should be hangingIndent
.
Allows setting the current indentation level.
A number could be passed in or the current indentation as text.
If I have a class with a property, then I would like to get an array of all types with generic.
Example:
class A {
private test: GenericType<AnotherType>>;
}
I would like to be able to call:
classDeclration.getProperties()[0].getType().getAllTypes()
and return ['GenericType', 'AnotherType']
- could not find it in documentation and tried many methods from Type interface. In the end I am processing compilerNode for it
As title.
Right now I'm using toString()
in some areas of ts-morph in order to check the previously written characters. This is obviously going to be slow, so it would be better if there were a way to iterate over the past characters.
I'm not sure how this would look though.
This would be some way to specify a max length for the line and then signify where line breaks should occur.
Similarly to the reason conditionalWrite
was introducted, it would be really nice if we were not forced to break the chain and introduce a for-of
loop with a single writeLine
call.
Something along the lines of the following would be great.
const indexes = [5, 9, 10, 15, 17]
writer
.writeLine(`return [`)
.iterateWriteLine(indexes, index => `this.array[${index}],`)
.writeLine(`]`)
As title. Will think this through later.
It will slow it down a bit, but doing writer.write("my string\ntest")
should:
\n
or \r\n
to the newline character specified when creating the writerEssentially, it should just take the inputted string and do:
(str || "").split(/\r?\n/).forEach(s => this.writeLine(s));
Add in future maybe: a function called writeWithoutAutoIndent(str: string)
for people to use to bypass this functionality?
Just cloned the repo and ran tests. They passed, but it ended with the following message
/home/lazar/code-block-writer/node_modules/coveralls/bin/coveralls.js:18
throw err;
^
Bad response: 422 {"message":"Couldn't find a repository matching this job.","error":true}
error An unexpected error occurred: "Command failed.
Exit code: 1
Command: sh
Arguments: -c gulp test && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js
Directory: /home/lazar/code-block-writer
Output:
".
Not sure what the whole thing is about so my only guess is that you're using some third party service and I don't have access to it?
I tried opening ./coverage/lcov.info
but have no idea what that's about 😅
This could be easily released for Deno. Probably it just needs to be bundled into a single file for release, but the best way to support both Node and Deno should be investigated.
For example the following:
writer.block(() => {});
Should output: "{\n}"
But if you do the following:
writer.block(() => {}).write("t");
It will do the newline after the block: "{\n}\nt"
Reason: I found if doing a block it would be annoying that it would automatically add a newline. This meant I would end up with code that looked like this:
function myFunc() {
func inner() {
}
}
Currently, the following throws (naturally) if foo
is null
.
this.conditionalWrite(foo != null, foo.bar)
However, this would not throw if the function was evaluated only after the conditional check has been passed:
this.conditionalWrite(foo != null, () => foo.bar)
We could still support the old one, of course, so it can be done as a non-breaking change.
Hi! Thank you for this library!
Is there any way to manage scopes of variables with it? For example, if I do some recursive code generation, at the moment I need to manage scope separately (mostly for capturing outer scope's variables).
Let's assume I generate some matrix processing code, and want to have some recursive function which generates the code. In that case I need to capture previous loop index somewhere, to then access it in the inner loop (and not use same i
variable name in the inner loop as well):
for (var i = 0; i < 10; i++) {
for (var i0 = 0; i < 10; i++) {
// access here both i and i0
}
}
It would be nice to have such feature in the library since it already is managing blocks and other scope-related things.
Sorry if expression of my thoughts is a bit messy, but I hope the issue is clear :D
I like block()
, quote()
, etc. But there are other pairings of tokens which are important: parentheses, square brackets, backticks for template strings, etc.
Suggested code:
pairedWrite(
startToken: string,
endToken: string,
newLine: boolean,
indent: boolean,
block: () => void
) : void
{
this.write(startToken);
if (newLine) this.newLine();
indent ? this.indent(block) : block();
if (newLine) this.newLine();
this.write(endToken);
}
Paired writes could also be useful for (// #region ...
, // #endregion ...
) cases.
The person using this library should just be wary about writing consecutive blank lines. Right now it's difficult to write many blank lines and that might be desirable.
This will close the comment if isInComment()
is true.
Newline for //
comments and */
for others. For */
it should do a space if there is a non-whitespace character in front of it on the current line.
Steps to reproduce:
npm install --save code-block-writer
import CodeBlockWriter from "code-block-writer";
it("CodeBlockWriter can be assembled", () => {
const writer = new CodeBlockWriter;
expect(writer).toBeTruthy();
});
tsc
for this file._00_shared_utilities/spec/CodeBlockWriterTest.mts(4,22): error TS2351: This expression is not constructable.
Type 'typeof import("/home/ajvincent/code-generation/cross-stitch/node_modules/code-block-writer/types/mod")' has no construct signatures.
Please advise.
TypeScript version 4.7.4
NodeJS version 16.14.0
As title.
If writeLine()
is the very first action it will cause a newline at the beginning of the file.
For example:
const writer = new CodeBlockWriter();
writer.writeLine("Test");
Will output a newline, then Test
.
For example, you should be able to write this:
function myFunc() {
const t = `some text
then on a newline`;
}
This is actually an enhancement and a breaking change. Basically, make this writer TS/JS specific.
Would indent the current line by the indent option.
For example:
writer.indent().write("test").newLine().write("test");
Would output:
test
test
Should be really easy to change this to not do .toString()
in these methods (which causes the internal array to be converted to a string).
Hey there,
I have installed the library using the command npm install --save code-block-writer
I have created a file main.js
then added the example mentioned in readme.
main.js file
const CodeBlockWriter = require("code-block-writer");
const writer = new CodeBlockWriter({
// optional options
newLine: "\r\n", // default: "\n"
indentNumberOfSpaces: 2, // default: 4
useTabs: false, // default: false
useSingleQuote: true // default: false
});
writer.write("class MyClass extends OtherClass").block(() => {
writer.writeLine(`@MyDecorator(1, 2)`);
writer.write(`myMethod(myParam: any)`).block(() => {
writer.write("return this.post(").quote("myArgument").write(");");
});
});
console.log(writer.toString());
then to run it I did node main.js
I am getting an error :
const writer = new CodeBlockWriter({
^
TypeError: CodeBlockWriter is not a constructor
at Object.<anonymous> (A:\practise\main.js:3:16)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.12.1
Sorry I never used JS/TS . So can you please tell me how to use it correctly.
Default to four spaces " "
, but allow the user to specify the number of spaces they want.
Same as block, but without the line break at the end.
const writer = new CodeBlockWriter({ useSingleQuote: true });
writer.quote(); // outputs: '
writer.quote("str"); // outputs: 'str'
This would be useful because then the quote style would be defined within the writer and code could be written the same regardless of the quote style.
I'm actually kind of confused about why I have a tab(times)
method, but not an indent(times)
method.
I kind of feel like the tab
method shouldn't exist because people should use indent
instead.
I've finally come across a scenario that I need this. Just work from the back of the array to find the position to insert at.
I find myself doing this a lot:
if (someCondition) {
this.writer.write("something");
}
This just takes up a lot of vertical room—especially since I usually add a blank line before and after if statements. It would be nicer to add this:
this.writer.conditionalWrite(someCondition, "something");
For example, if someone asks to write a space, then let them do so no matter what.
I'm using the latest version of ts-morph, Node 16, and typescript 4.3.5
Here's the source code of the class file
import React from 'react';
export class ClassComp extends React.Component {}
And here's the test code:
let exportedClasses: ClassDeclaration[] = project
.getSourceFiles()
.flatMap((file) => file.getClasses())
.filter((c) => c.isExported());
console.log(`Found ${exportedClasses.length} exported classes`);
exportedClasses.forEach((c) => {
console.log(
` Checking class ${c.getName()}
base types count: ${c.getBaseTypes().length}
Base class: ${c.getBaseClass()}
Extends: ${c.getExtends().getText()}`,
);
});
Output:
Found 1 exported classes
Checking class ClassComp
base types count: 0
Base class: undefined
Extends: React.Component
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.