I always wondered how I could properly add client-side JavaScript to 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 javascript.
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 missed some pretty important stuff, but I couldn't find any tutorials about it.
My question:
What is the "right way / best practice" to write client-sided javascript in Typescript / Express applications (which should also eliminate 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: