跳到主要內容

@babel/helper-compilation-targets

@babel/helper-compilation-targets 是一個輔助套件,可與編譯目標(瀏覽器或其他環境,例如節點)和相容性表格(知道哪個版本支援特定語法)搭配使用。@babel/preset-env 會使用它來根據 targets 選項來決定應該啟用哪個外掛程式。

JavaScript
import {
filterItems,
default as getTargets,
isRequired,
} from "@babel/helper-compilation-targets";

filterItems

function filterItems(
list: { [feature: string]: Targets },

// A set of plugins that should always be included
includes: Set<string>,

// A set of plugins that should always be excluded
excludes: Set<string>,
targets: Targets,

// A set of plugins that should always be included if `includes` is empty
defaultIncludes: Array<string> | null,

// A set of plugins that should always be excluded if `excludes` is empty
defaultExcludes?: Array<string> | null,

// A map from transform plugin to syntax plugin for backward compatibility with older `@babel/parser` versions
pluginSyntaxMap?: Map<string, string | null>
): Set<string>; // A set of enabled plugins

提供相容性資料表格 list(例如 @babel/compat-data)和 瀏覽器目標 targets,傳回所需的套件組。

範例

JavaScript
const compatData = {
"transform-feature-1": {
chrome: "1",
firefox: "1",
},
"transform-feature-2": {
chrome: "2",
firefox: "2",
},
"transform-feature-3": {
chrome: "3",
firefox: "3",
},
"transform-feature-4": {
chrome: "4",
firefox: "4",
},
};

// filter a set of plugins required when compiled to chrome 2
// returns new Set(["transform-feature-3", "transform-feature-4"])
filterItems(compatData, new Set(), new Set(), {
chrome: 2,
});

// filter a set of plugins required when compiled to chrome 2 and firefox 1
// returns new Set(["transform-feature-2", "transform-feature-3", "transform-feature-4"])
filterItems(compatData, new Set(), new Set(), {
chrome: 2,
firefox: 1,
});

// always include "transform-feature-2" and exclude "transform-feature-4"
// returns new Set(["transform-feature-2", "transform-feature-3"])
filterItems(
compatData,
new Set(["transform-feature-2"]),
new Set(["transform-feature-4"]),
{
chrome: 2,
}
);

// syntax-feature-2 is required to allow older @babel/parser to parse
// the feature-2 syntax supported in chrome 2

// returns new Set(["syntax-feature-2", "transform-feature-3", "transform-feature-4"])
filterItems(
compatData,
new Set(),
new Set(),
{
chrome: 2,
},
null,
null,
new Map([["transform-feature-2", "syntax-feature-2"]])
);
註解

當新的 ES 功能達到第 4 階段時,它將在 @babel/parser 中成熟,這表示它將始終被解析,而不管外掛程式為何。然而,我們需要語法外掛程式才能使用較舊的 @babel/parser

getTargets

type GetTargetsOption = {
// This is not the path of the config file, but the path where start searching it from
configPath?: string;

// The path of the config file
configFile?: string;

// The env to pass to browserslist
browserslistEnv?: string;

// true to disable config loading
ignoreBrowserslistConfig?: boolean;
};

type InputTargets = {
...Targets,

browsers?: Browsers,

// When `true`, this completely replaces the `browsers` option.
// When `intersect`, this is intersected with the `browsers`
// option (giving the higher browsers as the result).
esmodules?: boolean | "intersect",
};

function getTargets(
inputTargets: InputTargets = {},
options: GetTargetsOption = {}
): Targets;

將使用者指定的 targets 標準化為支援的目標清單。另請參閱 (@babel/preset-env)[preset-env.md#options] 以取得 GetTargetsOption

範例

JavaScript
// Return the default compilation targets
// returns {}
getTargets();

空的編譯目標等同於 強制所有轉換。預設編譯目標將變更為瀏覽器清單查詢 defaults, not IE 11 在 Babel 8 中。

也可以使用 ES 模組支援查詢編譯目標,例如 @vue/babel-preset-app 所做的,以提供一組現代目標。

JavaScript
/* returns {
"android": "61.0.0",
"chrome": "61.0.0",
"edge": "16.0.0",
"firefox": "60.0.0",
"ios": "10.3.0",
"node": "13.2.0",
"opera": "48.0.0",
"safari": "10.1.0",
"samsung": "8.2.0",
} */
getTargets({
esmodules: true,
});

注意:ES 模組相容性資料是由 MDN 所產生。

isRequired

function isRequired(
name: string,
targets: Targets,
{
compatData = pluginsCompatData,
includes,
excludes,
}: {
compatData?: { [feature: string]: Targets };
includes?: Set<string>;
excludes?: Set<string>;
} = {}
): boolean;

給定瀏覽器目標 targets,查詢 compatData 是否需要外掛程式 name 來進行編譯。當未指定 compatData 時,預設資料來源為 @babel/compat-data

範例

babel.config.js
module.exports = api => {
const targets = api.targets();
// The targets have native optional chaining support
// if `transform-optional-chaining` is _not_ required
const optionalChainingSupported = !isRequired(
"transform-optional-chaining",
targets
);
};

外掛作者可以使用 isRequired 來最佳化外掛輸出,以符合不同的 targets

example-babel-plugin.js
// a naive plugin replace `a.b` to `a != null && a.b`
module.exports = api => {
const targets = api.targets();
// The targets have native optional chaining support
// if `transform-optional-chaining` is _not_ required
const optionalChainingSupported = !isRequired(
"transform-optional-chaining",
targets
);
const visited = new WeakSet();
return {
visitor: {
MemberExpression(path) {
if (path.matchesPattern("a.b")) {
if (visited.has(path.node)) return;
visited.add(path.node);
if (optionalChainingSupported) {
// When optional chaining is supported,
// output `a?.b` instead of `a != null && a.b`
path.replaceWith(api.templates`a?.b`);
} else {
path.replaceWith(api.templates`a != null && ${path.node}`);
}
}
},
},
};
};

@babel/plugin-transform-object-rest-spread 使用 isRequired 來判斷目標是否已經有原生 Object.assign 支援。