Configuring ESLint and Prettier for TypeScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay I think we're good to go um good afternoon everybody Welcome to the latest edition of our virtual Tech webinar series um it's my great pleasure today to be introducing Josh Goldberg who's going to be talking today about configuring yes lince and pritzia the typescript um before we dive in just a quick word from our sponsors so this Meetup today is brought to you by blog rocket the vast majority of you for tuning in today we'll um probably have come from the blog but you may not know that we actually have a great product for when you're building and fixing applications so log Rockets is a front-end application monitoring solution that combines error tracking performance monitoring infrastructure monitoring and web analytics it's all rolled into one solution so your engineering and your product teams can all use a single source of Truth to look at all of these different aspects of app development this allows for more efficient remediation of problems and iteration and feature sets in addition to its integration with all of your existing back-end monitoring tools for more information head over to logrocket.com and you can get a personalized demo or you can sign up with a free account and just get a taste of what it can do for you uh uh I would like to just tip my hat in the direction of some future meetups that we have that you may be interested in um so we have on November 10th understanding reactive micro services with Jay hipster on November 21st scaling the testing pyramid with typescript and November 28th learns how to make a 360 VR video in unity if you're interested in signing up for more meetups you can just follow the link in the slide right here or you can just Google Virtual Tech meetups log rocket and it'll be the first thing that comes up now with all of that out of the way I'd like to welcome Josh to do his talk um and just a reminder to everybody that a recording of this session will be sent to you via email after the conclusion of the webinar now with all that out the way take it away Josh thank you very much and hi everyone thanks Jack I'm excited to talk to you today about typescripts and eslints and prettier these are a few things that tend to get confused a lot so I'm real pumped that we can try to shed some light on how they all work together um let me just go ahead and share screen everything that I'm going to talk to you today about is available online and I'm going to post these in the chat the repo that we're going to be working in is on my GitHub log rock at eslint pretty or typescript again I just sent it to the chat and a final version that has today's stuff along with a few other what I like to call bells and whistles is also on GitHub under my repo pardon me under my organization template typescript node package I'm going to be covering three areas of configuration today that I'll blend together and work well together we're going to be covering typescript the language that all of our code is going to be written in we're going to cover prettier which is the formatter and thank you Jack for posting in the chat and we're going to be covering eslint which is a static analysis linter for typescript meaning it looks at your code and gives you complaints potentially with autofixes without running it you can get started by get cloning this repo locally and I would encourage you to play along at home as I'm doing this stuff although you certainly don't have to the repo right now is pretty blank so we're going to be filling it out together it just has a license and a readme with a few links the first thing to do when you're setting up a node package is make a package.json and I'm just going to put a few quick pieces of information there author is let's just say Josh Goldberg Joshua cablework.com and I'm gonna add a dependency now you can either add a dependency to the command line let me just maximize this with something like 10 PMI typescript say oops saved of or if you use a nice editor that has fun features the way vs code does you can do something like dependencies typescripts probably rather Dev dependencies typescripts and then wait for it to autocomplete the version which is my preferred way because I enjoy that um it also as Jack says I also want to call out I'm going to just keep going through all these things please do ask any questions in the Q a I will try to answer them in real time if they're relevant in something that we should talk about or if not sorry if we should talk about in the moment and then anything else that gets left over I will try to answer at the end I've also seen people question what is the difference between dependencies and Dev dependencies dependencies is anything that you want to get packaged along with your package when you publish it Dev dependencies is stuff that on top of those should be available when you develop locally so typically typescript is a Dev dependency because you don't need people to also download and install typescripts when they run most packages that's that's a development time tool type cube is a programming language and a set of Tools around that language not something you would use at runtime for the most part so when we add temp dependencies typescript we are saying I want typescript to be available for me as a developer while working on this package foreign you can use any package manager you want npm or yarn or pnpm or others I'm sure they exist for now I'm just going to use npm because it's the one that everyone should have locally with node and immediately we see after npm installing my added one package I have 193 changes in my source control I have packagelog.json package.json and then a whole bunch of stuff in my node modules that's because by defaults it does not ignore anything but we should ignore the node modules directory you can get there are some projects that check in node modules but that's out of scope for this Workshop now that we're ignoring node modules in our git ignore I'm going to say that's our first pause Point add all good limit and installs the dependency typescript and get pushed hooray I'm going to keep doing these pushes throughout the workshop so if there's ever anything you're confused about you want to see the code that I'm writing feel free to check it out on the repo on github.com Joshua pay Goldberg slash log rocket eslints prettier typescript and in case you haven't inferred it by now I will explicitly say we are doing this from scratch so there might be some small hiccups if I miss type a command somewhere but for the most part I want to show y'all the experience of building up a repository from nothing to a fully fledged typescript eslint prettier setup foreign now that we've installed typescript it's time to start using this I tend to write my source files in a directory called Source or SRC so I'm just going to do an console.log like Hello World and I cannot run this file immediately because it's in typescript so it's the typescript syntax now in theory we can do node source index.ts and it just coincidentally works because so far we haven't written any types of specific syntax but if we do something like export type equals true and then try to run it in node node would complain um first of all I would using uh export syntax and that's uh that's too new for node I'll cover that in a bit second of all we're using specific typescript syntax which node doesn't understand in order to compile this index file into a JS file we're going to need to call typescripts which I typically do under a build script build TSC in your package.json you can have a list of scripts as key value Pairs and then run any of those scripts NPR one build runs the TSC script which is the typescript command line however by default TSC doesn't do anything it just shows you a bunch of utilities or common commands you can run with it because you need to configure typescripts perhaps you need to know on what files it's supposed to run and with what settings with npm run scripts you can pass in after a dash dash a list of flags or command line options for example you can pass in index.ts to have it builds pardon me Source index TS there we go and now in our source we have an index.js note how the typescript specific syntax here is removed and we just have the JS syntax if you're not too familiar with typescript yet that's okay I'm not going to cover the specifics of what a type is or how type inference works just know that typescript files contain JavaScript syntax plus some new stuff that gets spit out trimmed out when you turn it into Js I will also note that our source slash index.js is being tracked by gits which we don't want so I'm going to also add Source star star star.js to our getting door so that no more source files or Source directory files with JS as their extension are left all right now in order to run our files we need to have a main that tells node that if someone were to import our package say require parentheses log rocket typescript there would be a particular file that gets run as the main so here if we if someone in theory were to run node and then x equals required the path to log rocket to use some prettier typescripts the thing that would get given back to them is the results of running the index.js file and you can see that because I've run require on the current directory it's as if someone is requiring or importing my package which means we console log hello worlds in fact if we do that again and you know I'm just going to say module.exports.lo equals world and then require dots we see that in addition to logging hello world we also get that nice hello colon worlds module exports so hooray someone could in theory import our package if we were to publish it though publishing does require a version so let's go ahead and add let's say zero zero now I'm a big fan of modern features and using the latest and greatest for everything so instead of using the old common JS exports format I'm actually in my index TS file going to say export const uh value or hello people's world and then if we rerun Builds on it we get typescripts to do some magic to compile this down to what looks like common Js I actually I don't really want this to be in common JS I want to be in module BS next I think it is there we go export bar hello equals world so now we have a build output using this lovely little build command we're saying to typescript well first build using TSC we are going to build the source index file and then the module we're going to use as es next meaning the output module is yes next instead of say common Js so that's common.js this is yes next if you're not familiar with JavaScript modules that's okay there is a whole bunch of stuff from old module formats such as common JS the one that node uses by default and now we have a new unified module format ecmascript modules or ES modules and I'm going to go ahead and say in my package that I use the es modules for module by default so now when someone requires the package say require dots oh boy I can no longer require it but I can import dots pardon me uh the rebel is a little here we go you know what I'm just gonna give up on that well we have stopped people from being able to require that but now we are using the nice proper new aquascript module syntax and one last thing I want to note before committing is that this is a long build command I don't want to have to memorize that or put in the readme so I'm actually going to make a tsconfig.json file where I store the compiler options module yes next so now if we run mpm1 build it'll pick up that there's a tsconfig file and run on all Ts files in our current directory excluding node modules which is great just whoops I hit the wrong thing just to show that this is updating I high yay npm run build we get the updated output yay so to recap we have changed our package from a common js1 that defaults to ecmascript module is the fancy new thing in node by adding in type module and telling our TS config that our module is yes next we've added a build script that runs TSC we've added an index file and locally we can see that there is a source index.js created as a result we have mostly configured typescript now initial typescript config there are a few more flags that I want to cover with typescripts one is the target flag you may have noticed that we have slightly changed the JavaScript syntax in creating our index.js the original file used const while the output file uses VAR for those who haven't used old JavaScript before there are a lot of older ways of doing things in JavaScript that have been replaced or augmented with new base for example we no longer need to declare variables with the VAR which has weird scoping semantics we can then instead use less or cost but typescript by default down piles or transpiles to an older version of ecmascript or JavaScript any code that it's given by default it sets its Target to ES3 which is the oldest supported JavaScript that it could care about but we want to Output to newer JavaScript there's no need to support ES3 anymore or even es5 fun fact the vast majority of users are running on evergreen or constantly updated environments and you can unless you're supporting weird old Legacy users probably use es2021 and almost certainly use es2020 as your target if we run npm run build again after changing our Target to es2020 we see that our output is const and I'm getting a little annoyed here because I keep having to run build so I'm going to actually add a dash dash watch flag in my terminal which will run build in watch mode npm run build space dash dash space dash dash watch or just SW start a compilation in watch mode found zero readers waiting watching for file changes now you can see in glorious real time as I switched my target round and round we got different JavaScript output and if you want to see some really fun stuff here declare an async function hello that like return awaits like awaits promise that was all hi what is this complaining about oh it's a duplicated identifier test here we go you can see the Glorious amount of stuff that typescript adds in order to support older JavaScript runtimes if we were to change our Target ES3 we get a full shim or working version of generator code which is a JavaScript language feature that async awaits is built on but if we switch up to the es2021 let's say we see that typescript is just outputting async and awaits natively the runtime its targeting supports it so it doesn't need to down pile or transpile to an older JS version okay so that's great that means we can commit targets es2021 I will again notes that I'm just barreling forward with all this stuff so please let me know if there's anything that you wanted to ask about if there's anything unclear any little edge cases in typescript you'd like more information on I'm going to try to spend roughly a third of an hour on each of typescript prettier and eslint prettier is going to go a little short eslim is going to go a little longer a little bit more on typescripts I'm not going to go too deep into these but a few more Flags es module interrupt true is often a good idea because there are two different module formats common JS and Es modules that a lot of packages might need to support one or both of sometimes there's a weird discrepancy between one or the other and it can be difficult for your code to correctly import a package es module interop tells typescript to assume that you are using some sort of runtime like webpack or veets that massages that a little bit makes it easier for you um by the way if you ever get curious about these flags um you can always hover over them in your Editor to get the link huh didn't know I didn't trust typescript Lang and you get taken to this beautiful page typescriptblind.org tsconfig you can also find this page from AKA dot Ms slash gsconflict which takes you straight to the page and then you can search GS module interrupt for example to see how these flags change how typescript changes your code most of these flags will do one or both of changing how typescript reports type errors and or changing how typescript emits code in this case es module interop it massages how typescripts imports Star as versus require as because that's a whole slight change between comma.js and Es modules I'm also going to add the flag skip lib check uh Skipper check tells typescript not to run type checking on DTS files that come in your node modules by default typescript we'll check your node modules and make sure the node type error is there however that's oftentimes not useful for two reasons one a lot of bigger packages have a lot of node modules which may conflict with each other have conflicting versions or modify Global variables in their type definitions in some weird way so you sometimes just need to disable them it also takes longer for typescript to type check the lore files it has to so anything you can do to trim down that list say removing node modules from it is good and useful so skip lib check is is nice I'm actually blanking on if there are any other files that I want to show you being part of any config options I want to show you so I'm going to go ahead and check the template repo yes a few more and by the way under the template typescript node package you can always check blob Main tsconfig.json uh let's see declaration it's great declaration tells typescript to generate a DTS file for each of your source files so I have created index TS and now since I've enabled declaration there's also an indexed ETS these DTS files or Declaration or definition files oh how typescript can be told how JavaScript runtime packages work meaning if you publish a package to npm you're generally publishing the JS files these DTS files can then tell any consumer who's using typescript how those JS files look for those of you who do use typescript this may be uh obvious to you or important for those who you who haven't yet used typescripts trust me this is a very good thing and a big deal so highly recommend turning on Declaration 2 for your files I also am a big fan of Declaration map true and Source map true Source map turns on Source Maps so that someone using a debugger can uh visually view the the typescript files as the source it tells editors such as vs code and other debuggers such as Chrome how to visually display the source file when someone is debugging through the compiled output and declaration map is a little complex to explain but it creates a source map equivalent for DTS files that go back to the original TS source file so when you're using uh when you're using IDE features such as go to definition for packages it means that as a consumer you're able to look through the original source code which can be useful instead of looking at the compiled output DTS these again if you're not familiar with typescripts we can gloss over this but if you are using typescripts it is sometimes quite useful here we see index DTS index.js.map the contents of which we don't need to dive into deeply and then another map file for the DTs this is all looking good but I don't want to check in my DTS or map files so I'm going to get ignore BTS and also dots map files status now Joe shows just the they get ignore and the TS configured yay I'm going to connect okay source okay a couple more to go over um you don't need to set outdoor in my template node package I created a distant directory just to keep things uh separate but you don't have to outdoor tells typescript to shove everything that it outputs into a specific directory by default outdoor is whatever your Source directory is the lowest down common directory of all your source files which in this setup got inferred to be source so that's not something we need to focus on now but here we see one of my favorite Flags strict typescript is very configurable it can be configured not just to understand different JavaScript modules or whether to Output Source Maps but it can also change how strict it's type checking is is not strict by defaults meaning it is permissive by default but it can be told to be more strict with a large set of options the most important option there is strict Bell checking let's say you have a width name or a great name function name String I named to uppercase and you do green name and pass in a value that might be undefined map that oops not random greater than 05 Josh this is what a lot of folks call the billion dollar mistake if you've never heard of it before I will tell you it is believed to have cost at least a billion dollars in software damage the idea that you can pass in the equivalent of undefined or Anonymous language to somewhere that explicitly says it's supposed to take in a real type something that's not null or undefined if you instead set strict null checks specifically to be true types of people start yelling at you it'll say hey argument of type string or undefined the argument is something you give to a function is not assignable to parameter of type string because type undefined is not assignable to type string which means you have to fix your code let's say you put in a blank Anonymous placeholder or something strict null checks is one of several strict options of typescript has you can go back to that AKA dot Ms slash tsconfig page or just start typing in strict in your tsconfigs compiler options and you'll see a view of them the strict command on its own enables all of them but if you ever need to disable one like let's say strict function types is too difficult to implement which I won't get into now then you can always disable that and leave all the other strict settings on I highly recommend highly recommend always enabling strict whenever possible it's good for your code base and it lets typescript be as useful as possible I've got a permit this respect to true that's about all I wanted to cover with typescript let me know in the chat in the Q a if there's there's anything else you'd want to cover but with all that being said I'm gonna move on to prettier now typescript is a language meaning it's a set of syntax you're allowed to type in your source files and typescript also comes with a set of development tools it's got the TSC compiler that we're running in watch mode it's got a set of language services that allow vs code when you say hover over be able to show that variable is value prettier is a separate tool that applies formatting to your code the way prettier works is kind of cute I think it reads in a source file or a piece of text it parses it as an abstract syntax tree or AST which is a representation of the contents of that file that does not care about formatting then pretty or prints the file back using just the AST and whatever prettier settings you have so I'm just going to add a whole bunch of weird looking white space to this file just to really mess with it say with that formatting and then I'm going to go to the prettier docs because I can never remember the command that they have to get it started there's Docs man their vocal views here we go install here we go AMPM install save Dev same exact prettier which tells npm to use the exact version and then here we go npx prettier dash dash writes period which says run the prettier CLI and write mode on all the files in my local directory and voila prettier has Rewritten a whole bunch of my files to be pretty you may see that it normalized on my white spaces limited my end lines to one moved things onto the same line but reasonable awesome and that's a really useful command so I'm actually going to add it to my scripts format right here dash dash rate now if I do npm run format should pretty or write because I miss the dots hitting the wrong shortcuts here format there you go lovely if you want part of my laptop it's dying uh if you want you can always configure prettier using a prettier rc.json copy the command there your Json and then there are some options here now my editor here is suggesting these options because I have the prettier extension for vs code installed highly recommend installing this extension and in fact if you're using vs code you can have add to workspace recommendations done for any extension that you find particularly useful now if we go to dot vs code slash extensions.json we can see that it's been added here so anyone who opens this repo and Bs code will be prompted to install the prettier extension highly recommend it's great just as an example I'm going to switch to tabs instead of spaces for accessibility reasons and I'm going to npm run format again foreign I see a question great question what is the difference between installing the prettier plug-in and installing it as a dependency love the question I will answer live okay the dependency of your package Json tells npm that it needs to be in your node modules folder as a package because it is in your node modules folder and listed as a script that means that when you run MDM run format right here from from your neural modules is guaranteed to be in existence to be available and it'll run in your files so whenever you run npm run format or MPX prettier it'll run the node modules dependency that is totally and completely separate from installing prettier the editor extension the editor extension is something that'll run separately from your node modules separately from your scripts but it does modify your development experience just through your editor and I'm actually going to show from the templates typescript node package some vs code settings that are really useful here I recommend switching your default format or prettier and telling your formatter to be run on Save so I'm going to open another file here vs code slash settings.json and I'm going to wrap these Json so this is this is why part of why an extension is really useful because as you save a file it can have prettier run audience so I'm going to save that formatting and hit save and then we see that the file gets super nicely gratified whenever I hit save on it so that's the difference between the dependency which is something you can then run in the CLI and a plug-in or extension which allows your Editor to provide the features for you I'm going to mark this as done but please do ask another q a question if you think that that didn't sufficiently answer another one I noticed the prettier extension doesn't work without a prettier RC this isn't required installing it with npm interesting I have never actually tried to run without a pretty RFC but let's see what happens huh still seems to work I'm gonna reload my window maybe it's a cached setting you don't need a pretty or RC um oh yeah there we go if you're using it from the CLI I should say but I guess you do need the PRC if you're using the extension okay today I learned here I'm going to put this file back with your RC use tabs true there you go all right so we have configured prettier most but not all of the way that I will show we've configured it to run on Save in our editor and we've also added a format requires my package a format script that we can run on demand whenever we want so we're going to implement that initial add of the prettier there are a couple other times places ways that we want to run prettier a lot of people myself included really enjoy having prettier as a commit hook a commit Hook is something that's run by git on all your staged files when you try to make a commit it's really useful for say Auto formatters to make sure that if someone modified a file and then didn't save and prettier or didn't save through prettier didn't format it still gets formatted and because prettier is so quick it normally doesn't really irritate people too much I've seen people have like the entire test Suite of a repository run as a commit hook and that takes a while and is very annoying would not recommend so by the way there is a set of recommendations on the create your website my Chrome is freezing that's unfortunate I'm gonna close some tabs here oh boy part of my computer all right um here we go the pre-commit hook um ooh do I need to create a pretty RC file even the repo has the file to editor config I have never used an editor config file I'm aware that they're in existence but I do not know um that's like a totally separate tool um to my knowledge prettier does not read from an Editor to config but if if you have found some tools to let it do that then jolly good um I really like lint staged which is a tool that lets you run some commands on Commit so I'm going to copy and paste from the prettier docs npx mrm at two lint stage I actually don't know what mrm stands for but I have run this command enough times to feel confident in it this is going to modify my package to add lint stage here we go then staged and husky as dependencies this is we don't really have to cover the exact difference between lint stage and husky but the general idea is Husky sets up your git commit hooks their files in your repo that are used for them and then lint staged is what husky uses to call some commands I actually uh disagree with the default split stage settings here we see in our package I am actually charging it's just holding steady at seven to eight percent but thank you I appreciate it I'll let you know if it gets below six um the lint stage script will then run whatever whatever is in your lint staged uh object here so for every file that matches the JS CSS or MD description when you commit it'll have prettier dash dash writes right on it actually I'm just going to say let's run preview on everything and to put your dash dash ignore on down which is a command that's pretty or part of me a fly that Purdue can take into say ignore any unknown file so if I say checking a PNG file prettier won't try to how to format that it wouldn't make sense all right so get status hit add all we can actually see that we added a husky git ignore and a husky pre-commits you don't have to dig into this totally fine but this pre-commit file is what's run as a part of your git Hooks and it says that we need to run the lit stage command and notice one final piece of information before I summarize all this together we now have a prepare script that says husky install so going in order when we npm install npmi husky install will get run because that's the way npm works it runs the prepare script when you install husky will then install all these commits pardon me all these files such as dot husky slash pre-commit as githooks it'll then git will then be configured to run whatever is in these files on those respective hooks such as pre-commits which means it'll know to run lint staged lint staged is what will run pretty on our files so husky gets installed to run Lane staged when stage as a hook will run prettier fortunately none of us have to memorize any of what I just said because if you ever need to set it up it's on the prettier pre-commit hook docs but it's nice to know what all these tools do on the inside cool so now if I run here at all and I'm just going to add a chain change to my index file let's let's add some spaces save without formatting and let's actually get that all again hit commit and add it prettier now aha we see in my command preparing let's stage running tasks for staged files live modifications from tasks cleaning up temp files okay and during that commit you might have seen very quickly that it was running an index TS but now we can see that that space got removed that's about all I will show for now on prettier I'm now going to move on to eslims unless anyone has any q a questions for it eslint is my favorite part of this to give because I work on some of the tooling that goes into it and for trying to make it more simple over time all right let's talk eslint we've covered typescript which is the programming language we're writing in it adds nice syntax and Dev tooling around that syntax and we've covered prettier which is auto formatting prettier doesn't care about your code logic it doesn't care if your functions are named appropriately if your variables are used or whatever eslint is a linter and it cares somewhere in between those two things in fact I would say eslints can be considered to be run on top of typescript or on top of JavaScript eslens doesn't just check whether things are 100 guaranteed or likely to be correct it also detects for stylistic for naming conventions for likely bugs and the tooling that lets you run eslens on typescript code is typescript dslit the thing that I work on the tooling that enables the Islam to support typescript this is necessary because eslints on its own only understands JavaScript syntax by the way I love their new homepage they they added this relatively recently eslen finds and fixes problems in your JavaScript code it is not the same as typescript it is a tool completely separate from typescript that does not understand typescript on its own so if you want to run it with typescript go to the typescript eslint.io docs and add this lovely long command which adds an unfortunately large number of packages but I'll go through them in order it adds typescript DSL parser typescript dslip DSM plugin eslint and typescript as dependencies so really we're just adding two packages on top of via slides we're adding in a parser and an eslint plugin typescript eslint slash parser is what will be given to eslints to be able to parse our typescript code because again ESN doesn't natively understand typeship code but it can be configured to use a new different parser that can read in typescript so just quickly going back to the page we're going to create an ESL config file touch is our cscjs I'm going to copy and paste the contents of the file from the websites foreign so this configuration right here on line three says parser typescript eslen slash parser now eslint will know to run uh using the typescript BSN parser to be able to understand our code so if I do MPX es length Source index TS this should not throw an error yay and I'm also recommending part of me extending from the eslint recommended rule set more on the other things later so if I have an unused variable that's so far that you say bar hello equals true and I run eslint on the file hooray we get a complaint unexpected various letter counts instead now I've also left out a few points of configuration from the explanation typescript dslant has its own set of recommended rules so we recommend that you in your ESL config extend from slint recommended and plug in typescript dslip recommended this gives you the recommended set of rules for modern JavaScript typescript code bases things like don't use VAR use lettercast foreign we also have a no unused vars Rule and typescript which by default gets configured to warning it's a good warning to have though and two more pieces of config to go through we have the plugin typescript via slits that is the package that I installed uh type Cube ESL plugin and the eslan plugin is a set of rules that are then made available to eslint by default EOS lens doesn't recognize any rules other than just the default ones that it comes with by installing as a dependency type GPS slash ESL plugin you can now access rules such as r no unused variables Rule and the extension lists that config recommended so that's really important and good at useful lastly this root true flag here this tells eslint that this config is the root of a repo so far in eslints you can put es link configs nested within subdirectories like you might have one within a test directory or within a particular package they're slowly going to be moving away from that system in the future but for now this root true is a good thing to have it tells eslint to stop looking for configs Above This directory in your folder structure all right so we've added easily we've added typescript eslint so that it can run out of our code and we've added an intentional failure to our code uh commits now initial distance a few things on top of this um it's always good to have a package script so I'm just going to add a script limits yes that's Dot that so let me just make sure that's gonna work mpm run list aha now we are seeing that our eslints on dot instead of index.ts is running on our JS files as well and I actually forget how to uh how do I configure this in my other repo so I believe there's an eslantic nor file nope package Json lens oh you know what we can he just selecting more okay so I'm going to touch that is link to ignore you select ignore and star.js I think it is and the other one we ignore the District directory but here we're doing them in line okay so now we're ignoring a JS file because we only want to lint our typescript files and fun fact you can also run lens or eslint in dash dash fix mode to tell it to autofix anything that it can here I see we uh we don't have any available Auto fixing but if we change this to Let's then I'm betting that it'll give us a different complaints hmm uh you know what here we go let I've the issue is that I named two variables the same thing okay there we go we have one error potentially fixable with the dash dash fix option so if we do links dash dash fix it'll switch this to const there we go so that's so useful that I though I don't always do this I've seen repos do lint colon fix but eslints uh best aspects or I'm here run let's dashed aspects npm run links events there you go um I also see that there is a warning now the purpose of a warning in eslint is kind of vague some people interpret it to be it's okay to have it some people think it's not okay my personal philosophy is that you should only ever use warnings as a way to migrate to enabling the rule that rule should basically always be errors I've seen too many code bases where people leave a bajillion warnings in and then developers get accustomed to seeing little yellow squigglies it's a whole pain in the butt I hate it so I highly recommend either configuring all your rules to be errors or running with the uh dash dash Max warnings zero flag which tells oops tells es links as the name suggests you're not allowed to have more than x warnings and it'll exit with an error code if you have more than the maximum maximum zero means any warning causes a failure I also recommend the reports on use disabled directives flag fun fact I added that one where if you disable a lint rule and that's a later on change your code to no longer need it um eslint will give you a complaint saying hey this this disable next line is um no longer necessary so you can get rid of it fun fact some people think that eslint blocks the build esletch is never a build blocker because you can always disable a rule for a file on a particular line in a range in a file or just in your eslens config altogether if we say didn't want to use no unused bars we could always put Google's security distance no unused Mars true or F there we go then if we were to rerun again we'd have two complaints about unused ESL disabled directives so I I never want to hear anyone say oh I couldn't possibly check this pull request in eslint is complaining no you can always disable eslints on a per line for file per repo basis not that I recommend it but those options are there all right I do see a couple of Q and A's very good questions let me just commit uh wanting some Lauren my commit messages get worse as the workshops go on there we go um is it possible to configure es link to choose a parser depending on file extension yes it is in fact some people have to do this with view because view has its own parser which then may or may not need to call the typescript Via Slims it's doable with overrides and this is actually quite common in ESL configs so you can override certain files let's say you want to Dot View and you can override to have a parser if you I figure out what the view parser is called so it's called smiley face um this is this is actually pretty reasonable and common for people to use not just to override the parser but also to override your rules list for example in your test files you might override the rules to say typescript instance know on the safe um Star by Sunset Penny to be I forgot there are a few types of BSN rules that tend to conflict with tests excuse me specifically with the expect API from just and similar so actually you know what I am forgetting them so let's go to the typescript eslints docs and look at their rules how unsafe is used or is it Dash penny aha here we go no unsafe assignments or call I think it's the one so let's say that you're writing tests and you're using expect and you're constantly getting complaints in your test files that you shouldn't about no one say call you can always disable it for specifically your test files with an override so I hope that answers the question let me know if there's more info you want there can you add a linter oops answer live can you add a Linker in the pre-commit book as well great question yes you can you can add whatever the heck you want to hear you could do star and then star.ts npm run lit or just eslints or something um I do not recommend this though um I do not recommend this for typescript projects or in JavaScript because people get really annoyed when you have git commit hooks that take a while or May Fail the proper time to be running lints is at development time and the proper time to be validating it is in your CI which I haven't even got into but will soon having say GitHub actions or Circle Ci or similar verify so you can do this you can put whatever arbitrary command you want Inland staged but I recommend keeping it to things that are very quick nearly instantaneous like prettier good question so I'm gonna disconnect copyrights yes oops commit Dash yeah the last thing that I will cover with linting before we we show some actual CI workflows is typelinting because this is a very important thing an advantage that typescript PSN gives by default eslints even when running with type GPS doesn't have access to type information meaning it only sees the structure of the code it doesn't understand what types things are it wanted to understand if you say import something from a package what type that thing is that's typescript information if you configure it to it can run with a lot of much more powerful rules that can use that type of information [Music] I'm gonna copy and paste some of this extra information here let's see through set it to Dot and oh wait no door name is fine and recommended we will stick to do so here we are saying oh boy there we go here we are saying that I have made for these two changes my parser options oh no I shouldn't have gotten rid of parser pardon me parser typescript Dash yes parser here we go we're saying that the parser is going to be configured with the project that project means that typescript is like when parsing your code can also build up type information from your code based on that TS config then we also enable the recommended rules from type pts like that require type checking they are not in the default recommended rule list because by default there is no type information but recommended requiring type checking does enable these rules and some of them are surprisingly powerful one of my favorite ones is typecasting let's say that you allow name to be string or undefined and or even just let's say Name by defaults equals anonymous and let's say you have some code that runs it famous to find and you're like okay if name console.log name as string type group BS lint has a rule that will tell you hey this assertion is unnecessary since it does not change the type of the expression part of my mouse and then you can Quick Fix using the eslint extension your editor or just eslints Dash Dash face final command line notice how it does take a little bit longer to build up that type information and I'll cover this error message in a hot moment but it does fix it very nice which reminds me let's add the eslints extension to our workspace recommendations so if we go to our PS code extensions we now also get this person this is BS code eslens yeah at all status typed lynching and and extension now there's one more error message I want to fix before we're done with type linting and it's this parsing error parser options that project has been sets blah blah I actually have an open pull request in typescript PSI to improve the Sarah message but if you ever see it the the thing that it's complaining about is that it's trying to run eslints on a file that is not included in your TS config that's an error because there's no type information available for files not in the TS config so to fix it you have a few options one is you could be a slim to ignore your CJs file goes away the other is you could add it to your TS config or you could use an override to say only enable parser options typescript eslints and so on for your typescript files so star.ts star in case that's 2 plus X parser options and extends voila so now oops restart the slide server this one I'm I'm not super confident about is the right way I'm thinking it's complaining about this one still so personally I don't I don't spend much time trying to get that to work I just removed my esm file from the from the list of linted files there is probably some way to get this to work let me know if you find it because I've had only irritation there so ignore CJs ooh question from the Q a I'm having trust I'm having trouble with one rule in particular types could be a slant no floating promises error ah fun fact I wrote the original no floating promises and I feel your pain it used to be even harder to work with types could be a no floating promises it's a very opinionated literal um I don't think we have time to cover it now but please do reach out to me on Twitter or uh email if you want some help with that um as a rule it stops floating promises so promises that aren't handled in some way like with a DOT then or no weights or a DOT catch but uh you oftentimes you may end up just needing to be a slim disable a next line for a floating promise such as life um okay one final thing to cover is running this stuff in CI the last thing is I'm gonna just quickly Breeze over these because I wanted to end after about an hour and it's about an hour um I highly recommend adding a workflow in whatever CI provider you use for each of these commands and I'll just build one up real quick let's add in a GitHub build commands which will run your npm run build so I'm going to make their GitHub slash workflows touch oops I have to dash speed on that like enter sorry my zoom stuff's in the way maker.github Victor workflows touch the Guitar Works workflows build yaml there we go all right so this will use the latest version Ubuntu whenever we push to the main branch or send a pull request or commit to a pull request we'll have a build job that checks out the repo and then uses this GitHub actions prepare which I will approximately copy and paste from repo dot GitHub actions slash repair slash action catalog let's have a dash p no it doesn't or buddy here Dash p touch action gamble I really like having a reusable uh setup or prepare action which sets up a repo in CI here we have setup node which does mpm install um after setting up node with no version 18. so putting these two together I in this GitHub workflow is building ml say to with the latest version of npm run the npm build script it commits and assuming I haven't forgotten anything or left in a reference to yarn or some such now if we go to the log rocket repo which I've managed to close somehow go to the actions tab we can see one workflow run from added build.yaml very exciting it's got just the one job build running npm run build and it passed Yay good for us since build works I'm going to get aggressive and also add formats Dot yaml all this uh format and I'm going to also add a links.ie ml2 foreign now I should note actually format does require another command line flag or is it oh I called it prettier in the temporary well um I highly recommend dash dash list difference which will tell it to complain if there are any different things so let me just go ahead and add that to the gavel balance Dash Dash list difference okay so at this point we've pretty much completed the workshop and I'm going to recap all the things we did because I realized there are a lot of files first we added a basic package.json and actually let's just go to the commit history I'll look through those we added a basic package.json we added typescript as Dev dependency with a typescript config we set our Target to es2021 so that we don't have to transpile down to Old syntax we set up the package with a main so that it can be run we configure typescript to include Source maps and definition maps and definition files along with strict true avoiding the billion dollar mistake we added prettier as a CLI flag whoops as a CLI flag and as a commit hook we then added eslints not as a commit hook just as a CLI then we also enabled eslint to run with the fancy schmancy powerful typescript empowered rules we then fixed up a CJs complaint with eslints and then we added eslints typescript and prettier as CI oh look at this CI that gets run via GitHub actions at this point our repo is pretty much ready for any sort of typescript related changes that might get thrown onto it later on you might want to also add say testing or automated releases and if you do I'd encourage you to check out this rebound template typescript node package but for now that's that's pretty much all I wanted to cover thanks y'all for listening and I now open the floor to any other questions or comments y'all wanted to post in the Q a and if anyone still has issues with no floating promises you and you want to post more specifics I'd be happy to answer those now thank you so much for the talk Josh and thank you everybody for your questions uh we had a lot today which was uh really great um if anyone has any final questions that I'd like to ask Josh now's the time before he um before he leaves um I actually I see the question um parser error project has been separated yes I'm parser this this was covered but I also just want to show a pull request that we will be releasing and and as soon answer or soon released version of typescript DS links um Jack I just sensed to host and panelist if you don't mind forwarding over so this this PR includes a link to an issue and also much better error messages for that specific complaint the specific complaint is saying that you've told typescript PS lens to run with type information but there's no type information available for that file because it's not included in your TS config so my suggestion would be to either include that file in your TS config or just excluded from lighting altogether okay great um just a final reminder to everybody watching that we will be sending a recording of this uh after the webinar is concluded um I'll be emailing uh afterwards of the link to our YouTube channel where we'll be uploading and you can watch it your convenience again whenever you wish to uh just like to thank Josh once again for joining us for a second time it's been absolute pleasure to have you come and deliver another talk for us and I think we might have one last one last question yeah I have a question out of this Workshop scope maybe well I have a problem with prettier extension and it keeps overriding on any setting I put in my vs code setting file ah this is one thing I didn't go over but could have and arguably should have eslint config prettier sorry Jack one more thing uh npmi saved eslint config prettier oftentimes you will have lint rules from eslint that conflict with the prettier settings eslint is really really bad at formatting and that is not a case that you want to have happen so you never want to have um you never want to have ESL rules that conflict with prettier the structurally eslint was not made for formatting so it has a lot of edge cases and it's slow when it's trying to do them so highly recommend ESL config prettier add it to your extends list and then this should never go away or this should never happen it should go away so let's say you accidentally have some ESL rule that changes white space or endlines or something add the prettier extends in your ESN config and that should go away if you have other issues with the prettier extension overriding your vs code settings file that's I I would encourage you to email or Twitter at me that one I can take a look yeah this is different from a useless plug and prettier which allows you to run pretty or through eslint which is slow and I would not recommend okay now we're done I think okay okay uh once again just thank you to everybody for your questions it's just been really great to have that engagement from everybody and thank you Josh once again and thank you for joining us today and wishing everybody a great weekend thank you
Info
Channel: LogRocket
Views: 14,788
Rating: undefined out of 5
Keywords:
Id: 11jpa8e5jEQ
Channel Id: undefined
Length: 70min 32sec (4232 seconds)
Published: Fri Oct 21 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.