Skip to content

v1 TypeScript

Jonathan Sharpe edited this page Aug 24, 2024 · 1 revision

starter-kit-ts isn't actively maintained, but shows how the starter kit can run with full-stack TypeScript. The steps, as of last time I needed to do this, are:

  • Remove Babel and the Webpack loader:

    $ npm uninstall @babel/{cli,core,eslint-parser,node,plugin-proposal-class-properties,plugin-transform-runtime,preset-env,preset-react,runtime} babel-loader
    

    and delete all of the .babelrc files.

  • Install TypeScript with the relevant types and helpers:

    $ npm install --save-dev typescript ts-{jest,loader,node} @types/{jest,morgan,node,react,react-dom,supertest} @typescript-eslint/{eslint-plugin,parser}
    
  • Update the scripts in package.json:

         "prebuild": "npm run cleanup",
         "build": "npm run build:server && npm run build:client",
         "postbuild": "./bin/build-info.sh || echo 'No build info'",
    -    "build:client": "webpack --config client/webpack/prod.config.js",
    -    "build:server": "babel server --out-dir dist --ignore \"**/*.test.js,server/static\"",
    +    "build:client": "webpack --config client/webpack/prod.config.ts",
    +    "build:server": "tsc -p ./server",
         "cleanup": "rimraf ./dist/*",
         "dev": "concurrently -k -n \"client,server\" \"npm run dev:client\" \"npm run dev:server\"",
    -    "dev:client": "webpack serve --config client/webpack/dev.config.js",
    -    "dev:server": "cross-env PORT=3100 nodemon --exitcrash --inspect --delay 500ms --watch server --exec babel-node server/server.js",
    +    "dev:client": "webpack serve --config client/webpack/dev.config.ts",
    +    "dev:server": "cross-env PORT=3100 nodemon --exitcrash --inspect --delay 500ms --watch server --exec node --require ts-node/register server/server.ts",
         "e2e": "concurrently -k -s first -n \"app,e2e\" \"npm run serve\" \"npm run e2e:safe\"",
         "e2e:dev": "concurrently -k -s first -n \"dev,e2e\" \"npm run dev\" \"npm run e2e:safe\"",
         "e2e:local": "cypress open",
         "e2e:run": "cypress run",
         "e2e:safe": "wait-on -l http-get://localhost:3000 && npm run e2e:run",
    -    "lint": "eslint .",
    +    "lint": "eslint . --ext=.js,.jsx,.ts,.tsx",
         "preserve": "npm run build",
         "serve": "npm start",
         "ship": "npm run lint && npm run test && npm run e2e:dev && npm run e2e",
  • Update the ESLint configuration in .eslintrc.json:

      "extends": [
    -   "@codeyourfuture/standard"
    +   "@codeyourfuture/standard",
    +   "plugin:@typescript-eslint/eslint-recommended",
    +   "plugin:@typescript-eslint/recommended"
      ],
    - "parser": "@babel/eslint-parser"
    + "parser": "@typescript-eslint/parser",
    + "parserOptions": {
    +   "sourceType": "module"
    + },
    + "plugins": ["@typescript-eslint"]
  • Update the Jest configuration:

    -module.exports = {
    +const typescript = {
            globals: {
                    "ts-jest": {
                            tsconfig: "tsconfig.test.json",
                    },
            },
            preset: "ts-jest",
    +};
    +
    +module.exports = {
            projects: [
                    {
    +                       ...typescript,
                            displayName: "client",
                            moduleNameMapper: {
    -                               "\\.(png|svg|jpe?g|gif|css)$": "<rootDir>/__mocks__/fileMock.ts",
    +                               "\\.(png|svg|jpe?g|gif|css)$": "<rootDir>/__mocks__/fileMock.js",
                            },
                            setupFilesAfterEnv: [
                                    "<rootDir>/client/setupTests.ts",
                            ],
                            testEnvironment: "jsdom",
                            testMatch: [
    -                               "<rootDir>/client/**/*.test.ts",
    +                               "<rootDir>/client/**/*.test.ts(x)",
                            ],
                    },
                    {
    +                       ...typescript,
                            displayName: "server",
                            testEnvironment: "node",
                            testMatch: [
    
  • Update the Cypress configuration:

    • e2e/plugins/index.js (note this remains JavaScript):

      -// eslint-disable-next-line no-unused-vars
      +// eslint-disable-next-line @typescript-eslint/no-unused-vars
  • Rename and update the Webpack configuration:

    • client/webpack/common.config.ts:

      -const HtmlWebpackPlugin = require("html-webpack-plugin");
      +import HtmlWebpackPlugin from "html-webpack-plugin";
      +import { Configuration } from "webpack";
       
      -module.exports = {
      -       entry: "./client/src/index.js",
      +const configuration: Configuration = {
      +       entry: "./client/src/index.tsx",
              module: {
                      rules: [
                              {
      -                               test: /\.js$/,
      +                               test: /\.[jt]sx?$/,
                                      exclude: /node_modules/,
      -                               use: {
      -                                       loader: "babel-loader",
      -                                       options: {
      -                                               cacheDirectory: true,
      -                                       },
      -                               },
      +                               loader: "ts-loader",
                              },
                              {
                                      test: /\.(png|svg|jpe?g|gif)$/,
                              template: "./client/src/index.html",
                      }),
              ],
      +       resolve: {
      +               extensions: [".js", ".jsx", ".ts", ".tsx"],
      +       },
       };
      +
      +export default configuration;
    • client/webpack/dev.config.ts:

      -const { merge } = require("webpack-merge");
      +import { merge } from "webpack-merge";
      +import "webpack-dev-server";
       
      -const common = require("./common.config");
      +import common from "./common.config";
       
      -module.exports = merge(common, {
      +const configuration = merge(common, {
              devtool: "inline-source-map",
              devServer: {
                      historyApiFallback: true,
              },
              mode: "development",
       });
      +
      +export default configuration;
    • client/webpack/prod.config.ts:

      -const HtmlWebpackTagsPlugin = require("html-webpack-tags-plugin");
      -const path = require("path");
      -const { merge } = require("webpack-merge");
      +import HtmlWebpackTagsPlugin from "html-webpack-tags-plugin";
      +import path from "path";
      +import { merge } from "webpack-merge";
       
      -const common = require("./common.config");
      -const { devDependencies } = require("../../package.json");
      +import common from "./common.config";
      +import { devDependencies } from "../../package.json";
       
      -module.exports = merge(common, {
      +const configuration = merge(common, {
              devtool: "source-map",
              mode: "production",
              optimization: {
              },
              plugins: [
                      new HtmlWebpackTagsPlugin({
      -                       scripts: [
      +                       scripts: ([
                                      { packageName: "react", variableName: "React" },
                                      { packageName: "react-dom", variableName: "ReactDOM" },
      -                       ].map(({ packageName, variableName }) => ({
      +                       ] as const).map(({ packageName, variableName }) => ({
                                      attributes: { crossorigin: "" },
                                      external: { packageName, variableName },
                                      path: `https://unpkg.com/${packageName}@${devDependencies[packageName]}/umd/${packageName}.production.min.js`,
                      }),
              ],
       });
      +
      +export default configuration;
  • Update the Dockerfile:

    - COPY ./.babelrc .
    + COPY ./tsconfig.json .
  • Add client/src/assets.d.ts to provide a definition for the import of logo.svg:

     declare module "*.svg" {
         const content: string;
         export default content;
     }
  • Add tsconfig.json files as follows:

    • client/tsconfig.json (used by Webpack):

      {
        "compilerOptions": {
          "lib": [
            "DOM"
          ]
        },
        "exclude": [
          "**/*.test.ts",
          "**/*.test.tsx"
        ],
        "extends": "../tsconfig.json",
        "include": [
          "**/*.d.ts"
        ]
      }
    • e2e/tsconfig.json (used by Cypress):

      {
        "compilerOptions": {
          "types": [
            "cypress",
            "@testing-library/cypress"
          ]
        },
        "extends": "../tsconfig.json"
      }
    • server/tsconfig.json (used by tsc):

      {
        "compilerOptions": {
          "lib": [
            "ES2021"
          ],
          "outDir": "../dist",
          "target": "ES2021",
          "types": [
            "node"
          ]
        },
        "exclude": [
          "**/*.test.ts",
          "**/*.test.tsx"
        ],
        "extends": "../tsconfig.json",
        "files": [
          "./server.ts"
        ]
      }

      Note: this assumes the default Node 16 runtime, per https://stackoverflow.com/a/67371788/3001761, see other versions of the question for other Node runtime versions.

    • tsconfig.test.json (used by Jest):

      {
        "compilerOptions": {
          "lib": [
            "DOM",
            "ES2021"
          ],
          "target": "ES2021",
          "types": [
            "jest",
            "testing-library__jest-dom"
          ]
        },
        "extends": "./tsconfig.json"
      }
    • tsconfig.json (used by all of the other configs, generated with ./node_modules/.bin/tsc --init):

      {
        "compilerOptions": {
          /* Visit https://aka.ms/tsconfig.json to read more about this file */
      
          /* Projects */
          // "incremental": true,                              /* Enable incremental compilation */
          // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
          // "tsBuildInfoFile": "./",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */
          // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */
          // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
          // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */
      
          /* Language and Environment */
          "target": "es5",                                     /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
          // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
          "jsx": "react-jsx",                                  /* Specify what JSX code is generated. */
          // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
          // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
          // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
          // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
          // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
          // "reactNamespace": "",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
          // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
          // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
      
          /* Modules */
          "module": "commonjs",                                /* Specify what module code is generated. */
          // "rootDir": "./",                                  /* Specify the root folder within your source files. */
          // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
          // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
          // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
          // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
          // "typeRoots": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */
          // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
          // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
          "resolveJsonModule": true,                           /* Enable importing .json files */
          // "noResolve": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
      
          /* JavaScript Support */
          // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
          // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
          // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
      
          /* Emit */
          // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
          // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
          // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
          // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
          // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
          // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
          // "removeComments": true,                           /* Disable emitting comments. */
          // "noEmit": true,                                   /* Disable emitting files from a compilation. */
          // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
          // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types */
          // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
          // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
          // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
          // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
          // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
          // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
          // "newLine": "crlf",                                /* Set the newline character for emitting files. */
          // "stripInternal": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
          // "noEmitHelpers": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */
          // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
          // "preserveConstEnums": true,                       /* Disable erasing `const enum` declarations in generated code. */
          // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
      
          /* Interop Constraints */
          // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
          "allowSyntheticDefaultImports": true,                /* Allow 'import x from y' when a module doesn't have a default export. */
          "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
          // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
          "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
      
          /* Type Checking */
          "strict": true,                                      /* Enable all strict type-checking options. */
          // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */
          // "strictNullChecks": true,                         /* When type checking, take into account `null` and `undefined`. */
          // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
          // "strictBindCallApply": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
          // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
          // "noImplicitThis": true,                           /* Enable error reporting when `this` is given the type `any`. */
          // "useUnknownInCatchVariables": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */
          // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
          // "noUnusedLocals": true,                           /* Enable error reporting when a local variables aren't read. */
          // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read */
          // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
          // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
          // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
          // "noUncheckedIndexedAccess": true,                 /* Include 'undefined' in index signature results */
          // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
          // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type */
          // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
          // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */
      
          /* Completeness */
          // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
          "skipLibCheck": false                                /* Skip type checking all .d.ts files. */
        }
      }
  • Rename all remaining .js files to .ts, except for:

    • __mocks__/fileMock.js
    • Anything in bin/
    • e2e/plugins/index.js
    • server/static/main.js
  • Fix any remaining type errors/lint warnings

Clone this wiki locally