Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share code between client and server side in a TypeScript web app

Tags:

typescript

I have a TypeScript project, and I have a data(.ts) file (what includes things like title) and I need it both server and client side.

My directory structure looks like this:

node_modules/
package.json
README.md
src/
    data.ts
    data.js (compiled data.ts)
    server.ts
    server.js (compiled server.ts)
    public/
        sw.ts
        sw.js (compiled sw.ts)
        [other static resources (.css, .html or other .ts)]

src/*.ts files are server side, src/public/*.ts files are client side.

So I want to import data.ts from both server.ts and sw.ts but require obviously doesn't work in sw.js.

How can I solve this? Or what directory structure would be better?

like image 345
Tamás Avatar asked Oct 18 '22 16:10

Tamás


1 Answers

I would organize as follows

src/
    common/
        data.ts
    server/
        server.ts
    client/
        sw.ts

And compile the whole thing to an outDir:../public. Also use module: commonjs .

CommonJS works out of the box with node (server) and webpack (client).

like image 199
basarat Avatar answered Oct 21 '22 01:10

basarat