Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup a SERVER side Node.js project to use Typescript and Webpack

I'm looking for resources (youtube or other articles) that show how to setup a server side Node.js project using Typescript and Webpack. I have found too many articles that describe adding typescript to a client/browser side project. I do not need to know this because I'm using Angular. I would like to use webpack, because that's what's embedded inside an Angular project, so using the same technology on the server would seem to make sense from a learning point of view. I can't seem to find the information I need on Typescriptlang.org. I know how to create a node.js project, so I don't need a node.js beginner tutorial/resource. The key thing here is how to add Typescript and Webpack to a Node.js server project. Thanks.

like image 268
Plastikfan Avatar asked Oct 18 '25 15:10

Plastikfan


1 Answers

It's not a lot different from the browser environnement configuration. First, you have to use the target option of Webpack to make your code compile for usage in a NodeJS environnement like so :

module.exports = {
    target: 'node'
};

Here's the documentation for this part : Webpack Targets

Also you have to make sure that you have @types/node installed.

A typical webpack configuration for this could be :

const path = require("path");

module.exports = {
    entry: "./src/index.ts",
    target: "node",
    output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, "build")
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: [ ".tsx", ".ts", ".js" ]
    },
}

Here a small working project I've made as an exemple : node-typescript-boilerplate

I recommend using the nodemon plugin for webpack : nodemon-webpack-plugin, it will help you to auto restart your app after each change to your code source.

like image 150
severin.julien Avatar answered Oct 20 '25 06:10

severin.julien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!