1. 程式人生 > 其它 >使用Bazel編譯TypeScript

使用Bazel編譯TypeScript

準備

請事先安裝Nodejs,Yarn 1.xBazel

我使用的版本為:

  1. Nodejs: v14.17.3
  2. Yarn: 1.22.5
  3. Bzel: 4.1.0

建立一個Typescript專案

選擇指定目錄,建立一個名為ts-bazel(其他名字也可以)的資料夾,使用終端進入該資料夾,然後執行npm init,一路選擇預設。

安裝Typescipt:

yarn add typescipt -D

建立Typescript配置檔案

npx tsc --init

建立src資料夾,在該資料夾裡新建index.ts檔案,並寫入一下內容:

function sayHello(name: string) {
    console.log(`helle ${name}`);
}

sayHello('daming');

配置Bazel

安裝bazel等相關依賴:

yarn add @bazel/bazelisk @bazel/ibazel @bazel/typescript -D 

在根目錄裡建立WORKSPACE, 並寫入以下內容:

workspace(
    name = "ts-bazel",
    managed_directories = {"@npm": ["node_modules"]},
)

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "build_bazel_rules_nodejs",
    sha256 = "275744d287af4c3a78d7c9891f2d970b7bc7eca8cfc0e9a671fe6258d09ff217",
    urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/4.0.0-rc.1/rules_nodejs-4.0.0-rc.1.tar.gz"],
)

load("@build_bazel_rules_nodejs//:index.bzl", "check_rules_nodejs_version", "node_repositories", "yarn_install")

check_rules_nodejs_version(minimum_version_string = "2.2.0")

# Setup the Node.js toolchain
node_repositories(
    node_version = "14.17.3",
    package_json = ["//:package.json"],
)

yarn_install(
    name = "npm",
    package_json = "//:package.json",
    yarn_lock = "//:yarn.lock",
)

在根目錄中建立BUILD.bazel檔案,並寫入以下內容:

package(default_visibility = ["//visibility:public"])

exports_files(["tsconfig.json"])

src資料夾中建立BUILD.bazel檔案,並寫入以下內容:

package(default_visibility = ["//visibility:public"])

load("@npm//@bazel/typescript:index.bzl", "ts_project")


ts_project(
  name = "index",
  srcs = ["index.ts"],
  tsconfig = "//:tsconfig.json",
  visibility = ["//visibility:public"],
)

編譯

現在可以使用bazel編譯專案了!

bazel build //src:index

檢查一下結果

node  bazel-bin/src/index.js

輸出結果為:

helle daming