JCafe
JCafe

Reputation: 597

Sharing code between node js project and a web site project

So I started coding a chess engine in typescript as a side project. I initially intended it to be a CLI like most other chess engines that interact through stdin and stdout. This so I could plug it to a GUI like Arena and test it against other engines. For that I decided to do it as a node project.

I set it across several files with 1 being the UCI (universal chess interface) implementation and the remaining ones chess logic and AI logic. After banging my head a few times trying to understand modules in typescript I finally got it to work.

Now I decided it would be interesting to write a simple GUI myself as a webpage with html+typescript+jquery. Now, I would like to use all the logic modules I wrote but I'm finding it impossible. From what I understand you can't use CommonJS in browsers so the only way I could get it to work was using instead internal modules for which I need to modify the .ts files to wrap the code in module X{ } blocks and recompile them just for the GUI every time I change something. This situation seems far from ideal and I was wondering if there is a way around it...

Upvotes: 1

Views: 880

Answers (3)

basarat
basarat

Reputation: 275917

I created a demo project to share code between the client and the server : https://github.com/basarat/demo-fullstack/blob/master/src/Gruntfile.js

It compiles the common files for both amd/commonjs and server files only as commonjs with the client only files as only amd. It uses grunt-ts to manage this : https://github.com/grunt-ts/grunt-ts

Upvotes: 1

Fenton
Fenton

Reputation: 250932

Use external modules for both the server and the browser.

When compiling for the browser, use the switch to specify the AMD module pattern:

tsc --module amd app.ts

And use RequireJS to load modules for you.

<script src="require.js" data-main="app.js"></script>

You will need to compile for the different targets, but the source code in TypeScript can be identical.

Upvotes: 1

glortho
glortho

Reputation: 13200

Use http://browserify.org/ to add CommonJS-like support on the front-end.

But also read this (slightly outdated) question and answer: How should I go about writing a node.js web application with both server and client side code?

Upvotes: 1

Related Questions