Skip to content

Latest commit

 

History

History
573 lines (482 loc) · 15.5 KB

setup.mdx

File metadata and controls

573 lines (482 loc) · 15.5 KB

import { Tabs, Tab } from 'nextra-theme-docs'

import Alert from '@mui/material/Alert'; import AlertTitle from '@mui/material/AlertTitle';

Setup

Summary

<Tabs items={['npm', 'pnpm', 'yarn']}>

npm install typia
npx typia setup
```bash filename="Terminal" showLineNumbers copy pnpm install typia pnpm typia setup --manager pnpm ``` Yarn berry is not supported. ```bash filename="Terminal" showLineNumbers copy yarn add typia yarn typia setup --manager yarn ```

If you're using standard TypeScript compiler, you can use transform mode.

Just run npx typia setup command, then everything be prepared.

<Tabs items={['npm', 'pnpm', 'yarn']}>

npm install typia
npm install --save-dev typescript

npx typia generate \
  --input src/templates \
  --output src/generated \
  --project tsconfig.json
```bash filename="Terminal" showLineNumbers copy pnpm install typia pnpm install --save-dev typescript

pnpm typia generate
--input src/templates
--output src/generated
--project tsconfig.json

  </Tab>
  <Tab>
```bash filename="Terminal" showLineNumbers copy
yarn add typia
yarn add -D typescript

yarn typia generate \
  --input src/templates \
  --output src/generated \
  --project tsconfig.json

Otherwise you are using non-standard TypeScript compiler, then you can't use transformation mode.

Instead, you can use generation mode.

Run typia generate command with input directory, then transformed TypeScript files would be generated into the output directory.

Transformation

Concepts

AOT (Ahead of Time) compilation mode.

When you write a TypeScript code calling typia.createIs<IMember>() function and compile it through tsc command, typia will replace the typia.createIs<IMember>() statement to optimal validation code in the compiled JavaScript file, for the IMember type.

This is the transform mode performing AOT (Ahead of Time) compilation.

<Tabs items={['TypeScript Source Code', 'Compiled JavaScript File']}>

import typia, { tags } from "typia";

export const check = typia.createIs<IMember>();

interface IMember {
  id: string & tags.Format<"uuid">;
  email: string & tags.Format<"email">;
  age: number & tags.ExclusiveMinimum<19> & tags.Maximum<100>;
}
```javascript filename="examples/bin/check.js" showLineNumbers {2-12} "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return mod && mod.__esModule ? mod : { default: mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.check = void 0; const typia_1 = __importDefault(require("typia")); const check = (input) => { return ( "object" === typeof input && null !== input && "string" === typeof input.id && /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test( input.id, ) && "string" === typeof input.email && /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test( input.email, ) && "number" === typeof input.age && 19 < input.age && input.age <= 100 ); }; exports.check = check; ```

Setup Wizard

<Tabs items={['npm', 'pnpm', 'yarn']}>

npm install --save typia
npx typia setup
```bash filename="Terminal" copy showLineNumbers pnpm install --save typia pnpm typia setup --manager pnpm ``` ```bash filename="Terminal" copy showLineNumbers # YARN BERRY IS NOT SUPPORTED yarn add typia yarn typia setup --manager yarn ```

You can turn on transformation mode just by running npx typia setup command.

Setup wizard would be executed, and it will do everything for the transformation.

Manual Setup

<Tabs items={['npm', 'pnpm', 'yarn']}>

npm install --save typia
npm install --save-dev typescript ts-patch ts-node
```bash filename="Terminal" copy showLineNumbers pnpm install --save typia pnpm install --save-dev typescript ts-patch ts-node ``` ```bash filename="Terminal" copy showLineNumbers # YARN BERRY IS NOT SUPPORTED yarn add typia yarn add -D typescript ts-patch ts-node ```

If you want to install typia manually, just follow the steps.

At first, install typia as dependency. And then, install typescript, ts-patch and ts-node as devDependencies.

{
  "strict": true,
  "strictNullChecks": true,
  "compilerOptions": {
    "plugins": [
      { "transform": "typia/lib/transform" }
    ]
  }
}

At second, open your tsconfig.json file and configure like above.

As typia generates optimal operation code through transformation, you've to configure it as a plugin. Also, never forget to configure strict (or strictNullChecks) to be true. It is essential option for modern TypeScript development.

{
  "scripts": {
    "prepare": "ts-patch install && typia patch"
  },
  "dependencies": {
    "typia": "^4.1.8"
  },
  "devDependencies": {
    "ts-node": "^10.9.1",
    "ts-patch": "^3.0.2",
    "typescript": "^5.1.6"
  }
}

<Tabs items={['npm', 'pnpm', 'yarn']}>

npm run prepare
```bash filename="Terminal" copy showLineNumbers pnpm prepare ``` ```bash filename="Terminal" copy showLineNumbers # YARN BERRY IS NOT SUPPORTED yarn prepare ```

At last, open package.json file and configure npm run prepare command like above.

Of course, you've to run the npm run prepare command after the configuration.

For reference, ts-patch is an helper library of TypeScript compiler that supporting custom transformations by plugins. From now on, whenever you run tsc command, your typia function call statements would be transformed to the optimal operation codes in the compiled JavaScript files.


**`npx typia patch`**

Since TypeScript v5.3 update, tsc no more parses JSDocComments. Therefore, typia also cannot utilize those JSDocComment related features too, especially "Comment Tags" and "JSON schema generator".

The npx typia patch command has been developed to revive the JSDocComment parsing feature of tsc. It is temporary solution for the TypeScript v5.3 update instead of ts-patch, and will be disabled after ts-patch starts supporting such TypeScript v5.3 update.

Of course, if you don't use any "Comment Tags" and "JSON schema generator", you don't need to run npx typia patch command. This is not mandatory command, but just optional command.

Generation

<Tabs items={['npm', 'pnpm', 'yarn']}>

# INSTALL TYPIA
npm install --save typia
npm install --save-dev typescript

# GENERATE TRANSFORMED TYPESCRIPT CODES
npx typia generate \
  --input src/templates \
  --output src/generated \
  --project tsconfig.json
```bash filename="Terminal" copy showLineNumbers # INSTALL TYPIA pnpm install --save typia pnpm install --save-dev typescript

GENERATE TRANSFORMED TYPESCRIPT CODES

pnpm typia generate
--input src/templates
--output src/generated
--project tsconfig.json

  </Tab>
  <Tab>
```bash filename="Terminal" copy showLineNumbers
# INSTALL TYPIA
yarn add typia
yarn add -D typescript

# GENERATE TRANSFORMED TYPESCRIPT CODES
yarn typia generate \
  --input src/templates \
  --output src/generated \
  --project tsconfig.json

For frontend projects.

If you're using non-standard TypeScript compiler, you can't use transform mode

  • Non-standard TypeScript compilers:

Instead, you should utilize the generation mode.

Install typia through npm install command, and run typia generate command. Then, generator of typia reads your TypeScript codes of --input, and writes transformed TypeScript files into the --output directory, like below.

If you want to specify other TypeScript project file instead of tsconfig.json, you can use --project option.

<Tabs items={['TypeScript Source Code', 'Generated TypeScript File']}>

import typia from "typia";

import { IMember } from "../structures/IMember";

export const check = typia.createIs<IMember>();
```typescript copy filename="examples/src/generated/check.ts" showLineNumbers {3-13} import typia from "typia"; import { IMember } from "../structures/IMember"; export const check = (input: any): input is IMember => { const $is_uuid = (typia.createIs as any).is_uuid; const $is_email = (typia.createIs as any).is_email; return ( "object" === typeof input && null !== input && "string" === typeof input.id && $is_uuid(input.id) && "string" === typeof input.email && $is_email(input.email) && "number" === typeof input.age && 19 <= input.age && 100 >= input.age ); }; ```
**Why not support non-standard compilers?**

Non-standard TypeScript compilers are removing every type informations, and skipping type checkings for rapid compilation. By the way, without those type informations, typia can't do anything. This is the reason why typia doesn't support non-standard TypeScript compilers.

By the way, SWC is preparing a new project STC keeping type informations. Therefore, typia will support it.

Vite

If you've made your frontend project through vite, you can still utilize the transformation mode.

Just configure vite.config.ts file below, that's all.

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import typescript from "rollup-plugin-typescript2";

// https://vitejs.dev/config/
export default defineConfig({
  esbuild: false,
  plugins: [
    react(),
    typescript(),
  ],
});

By the way, if you're composing monorepo, and need to import some external TypeScript files from the other package of the monorepo, you've to configure the vite.config.ts a little bit different. When declaring typescript plugin, you've to specify include and exclude options like below.

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import typescript from "rollup-plugin-typescript2";

// https://vitejs.dev/config/
export default defineConfig({
  esbuild: false,
  plugins: [
    react(),
    typescript({
      // WHEN MONOREPO
      include: [
        "./**/*.ts+(|x)",
        "../../core/**/*.ts+(|x)",
        "../../util/**/*.ts+(|x)",
      ],
      exclude: ["../../node_modules"],
    }),
  ],
});

Webpack

<Tabs items={['npm', 'pnpm', 'yarn']}>

# TYPIA
npm install typia
npx typia setup

# WEBPACK + TS-LOADER
npm install --save-dev ts-loader
npm install --save-dev webpack webpack-cli
```bash filename="Terminal" copy showLineNumbers # TYPIA pnpm install typia pnpm typia setup --manager pnpm

WEBPACK + TS-LOADER

pnpm install --save-dev ts-loader pnpm install --save-dev webpack webpack-cli

  </Tab>
  <Tab>
```bash filename="Terminal" copy showLineNumbers
###########################################
# YARN BERRY IS NOT SUPPORTED
###########################################
# TYPIA
yarn add typia
yarn typia setup --manager yarn

# WEBPACK + TS-LOADER
yarn add -D ts-loader
yarn add -D webpack webpack-cli

When you're using webpack as a bundler, you can still utilize the transformation mode.

Just install ts-loader as well as webpack, and configure webpack.config.js file like below.

const path = require("path");
const nodeExternals = require("webpack-node-externals");

module.exports = {
  // CUSTOMIZE HERE
  entry: ["./src/index.tsx"],
  output: {
    path: path.join(__dirname, "dist"),
    filename: "index.js",
  },
  optimization: {
    minimize: false,
  },

  // JUST KEEP THEM
  mode: "development",
  target: "node",
  module: {
    rules: [
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        loader: "ts-loader",
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
};

From now on, you can build the single JS file just by running the npx webpack command. By the way, when removing devDependencies for --production install, never forget to add the --ignore-scripts option to prevent the prepare script.

<Tabs items={['npm', 'pnpm', 'yarn']}>

npx webpack
npm ci --omit=dev --ignore-scripts
```bash filename="Terminal" copy showLineNumbers pnpm webpack pnpm install --production --ignore-scripts ``` ```bash filename="Terminal" copy showLineNumbers yarn webpack rm -rf node_modules yarn install --production --ignore-scripts --immutable ```

Additionally, if you're using typia in the NodeJS project especially for the backend development, Setup Guide Documents of nestia would be helpful. Even though you're not using NestJS, you can still utilize below documents, and "Single JS file only" mode would be especially helpful for you.

NX

<Tabs items={['npm', 'pnpm', 'yarn']}>

npm install --save typia
npx typia setup
```bash filename="Terminal" copy showLineNumbers pnpm install --save typia pnpm typia setup --manager pnpm ``` ```bash filename="Terminal" copy showLineNumbers # YARN BERRY IS NOT SUPPORTED yarn add typia yarn typia setup --manager yarn ```

After install typia like above, you have to modify project.json on each app like below.

 "targets": {
    "build": {
      ...
      "options": {
        ...
        "target": "node",
        "compiler": "tsc",
        "transformers": [
          "typia/lib/transform",
        ]
      }
    },
    ...
 }