I always wondered how I can properly add the clientsided javascript in my express project. I use Typescript and I would also like to take advantage of the Typescript typings (for jquery for instance) when writing my clientside javascripts.
My project structure looks like this:
What I have done until today:
I created all clientsided javascript files in wwwroot/js
(e.g. jquery.min.js, registration-form.js) and I loaded them into the header of the appropriate pages.
Disadvantages:
registration-form.js
into src/registration/
instead of the wwwroot)In some tutorials I saw they would simply run npm install --save jquery
and import it in their clientsided files. So I feel like I must have missing some pretty important stuff, but I couldn't find any tutorials about it.
My question:
What is the "right way / best practice" to write clientsided javascript in Typescript / Express applications (which should also elliminate also the mentioned disadvantages)?
Using TypeScript on the client side is not much different from the server side.
Here is what you can do:
client
folder for client-side typescript sourcestsconfig.json
into client
folder and configure it to produce "es5" code (target: es5)That's it, now you can write your client side code in TypeScript.
You can compile server-side code with tsc -p ./src
(having server-side tsconfig.json under src
) and compile client-side code with tsc -p ./client
.
I made a simple example of such app, check it here. I put the simple script to build everything into package.json, so you can run npm run-script complie
to get both server and client code complied into /dist
folder. Then run it with npm start
.
Further steps:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With