擴充功能檔案包含可匯入其他多個檔案的額外定義:
名稱一律以
.bzl副檔名結尾。必須屬於 Bazel 套件,因此會以標籤識別。 例如
//bazel_utils:defs.bzl。這些規則以 Starlark 語言編寫,且應遵循特定規範。
這是唯一可以定義 Starlark 函式的地方! 換句話說,您無法在
BUILD.bazel檔案中定義函式!即使匯入多次,這些模組一律只會評估一次,且定義的變數和函式會記錄為常數。
您可以使用
load()陳述式,從其他檔案匯入這些函式。
例如:
從
$PROJECT/my_definitions.bzl開始:# The official release number release_version = "1.0.0"從
$PROJECT/BUILD.bazel開始:# Import the value of `release_version` from my_definitions.bzl load("//:my_definitions.bzl", "release_version") # Compile C++ executable, hard-coding its version number with a macro. cc_binary( name = "my_program", defines = [ "RELEASE_VERSION=" + release_version ], sources = [ … ], )
load() 陳述式具有特殊語意:
第一個引數必須是
.bzl檔案的標籤字串 (例如"//src:definitions.bzl")。其他引數名稱匯入的常數或函式:
如果引數是字串,則必須是
.bzl檔案定義的匯入符號名稱。例如:load("//src:defs.bzl", "my_var", "my_func")如果引數是變數指派,則會定義匯入符號的本機別名。E.g.:
load("//src:defs.bzl", "my_var", func = "my_func")沒有萬用字元:所有匯入的常數和函式都必須明確命名。
如果
load()出現在.bzl檔案中,系統一律不會記錄匯入的符號。同樣地,名稱開頭為底線的符號 (例如
_foo) 絕不會記錄,也無法匯入。也就是說,這些函式僅適用於定義函式的.bzl檔案。
有時 .bzl 檔案會想從另一個檔案匯入符號,並以相同名稱重新匯出。這需要別名,例如:
# From //src:utils.bzl
# Import "my_vars" from defs.bzl as '_my_var'.
load("//src:defs.bzl", _my_var = "my_var")
# Define my_var in the current scope as a copy of _my_var
# This symbol and its value will be recorded, and available for import
# to any other file that loads //src:utils.bzl.
my_var = _my_var