Install TypeScript on Ubuntu

Posted on Wed 24 August 2022 in Javascript

Install Typescript

Install node and npm using apt:

sudo apt-get update
sudo apt-get install nodejs npm

Then, install tsc (TypeScript) globally:

sudo npm install -g typescript ts-node

Demo project

cd ~/git
git clone https://github.com/electron/electron-quick-start-typescript demo_app

This is the structure of the project:

 23:39:55 masterauraham@rocket ~/git/demo_app 
 > tree
.
├── index.html
├── LICENSE.md
├── package.json
├── package-lock.json
├── README.md
├── src
│   ├── main.ts
│   ├── preload.ts
│   └── renderer.ts
└── tsconfig.json

1 directory, 9 files

Install dependencies

cd demo_app

# install dependencies
npm install

# run the app
npm start

You will see a window like this:

[window]

Start local server at startup (did not work)

Let's modify the demo app to start a local server using the following command:

python3 -m http.server --directory ~/git/blog/public
vim src/main.ts
const isDev = require('electron-is-dev');

import { app, BrowserWindow } from "electron";
import * as path from "path";

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
    width: 800,
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, "../index.html"));

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  mainWindow.loadURL("http://localhost:8000");
}
vim src/preload.ts
const { exec } = require("child_process");

// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener("DOMContentLoaded", () => {
  const replaceText = (selector: string, text: string) => {
    const element = document.getElementById(selector);
    if (element) {
      element.innerText = text;
    }
  };

  for (const type of ["chrome", "node", "electron"]) {
    replaceText(`${type}-version`, process.versions[type as keyof NodeJS.ProcessVersions]);
  }

  // Start local server
  exec("python3 -m http.server --directory /home/auraham/git/blog/public");
});

Since we added two new dependencies, we need to install them:

npm install child_process
npm install electron-is-dev

This is a buggy workaround: run python3 -m http.server --directory /home/auraham/git/blog/public in a second terminal.

Then, start electron:

~/git/demo_app 
 > npm start

After that, you can close the second terminal and start the server with npm start.

THIS APPROACH DID NOT WORK!

Second attempt

References