My friend uses Typescript and Svelte to make web apps. I asked him how he chooses when something should be a Typescript file, versus when it should be a Svelte file; and he said, "in a svelte file it's code per instance of a component," whereas Typescript is "a regular file...global, one per application."
This makes sense to me logically, but I still can't comprehend when I should use which one. Is it possible to make the SAME exact web app using:
- ONLY Typescript files,
- ONLY Svelte files, and
- a mix of both?
If so, then why is option 3 superior? If not, which options are possible and which options aren't, and why? Better put, what (if anything) can Typescript files do that Svelte files can't, and vice versa?
CodePudding user response:
Svelte files can use special syntax for svelte components. Each svelte file is compiled into typescript file first.
And typescript files are usual files with typescript code.
So you need to put your components into svelte files and the rest of the code into typescript files. You cannot use svelte syntax in ts files. And you don't need it in usual ts files.
CodePudding user response:
Generally you would use Svelte files for Components, that is anything that will put something on the screen like buttons, links, containers, ... A Svelte file would typically consist of three parts (but not all are required).
- markup, the stuff that gets rendered to the screen
- styling, css to make the markup look nice
- script, some variables, eventhandlers, etc that go with this markup
In your JavaScript (TypeScript) files you have code that is not directly related to the user interface. Here you will typically find utility functions, stores, apis, ...
Commonly Svelte components will import some of your JavasSript files and use the functions defined there, this can be because this function is used in different places (for example a function that formats dates) or simply because it is a long and complicated function and you want the Svelte file to be short and clean.
In other words, if you choose to make an app with Svelte (there are other options) you will use a mix of both Svelte and JavaScript files that serve two different purposes.