依赖解析

当 Parcel 构建源代码时,它会发现依赖,从而允许将代码分解为单独的文件并在多个位置重用。依赖描述了在哪里可以找到包含你所依赖的代码的文件,以及有关如何构建它的元数据。

¥As Parcel builds your source code, it discovers dependencies, which allow code to be broken into separate files and reused in multiple places. Dependencies describe where to find the file containing the code you rely on, as well as metadata about how to build it.

依赖说明符

#

¥Dependency specifiers

依赖说明符是一个字符串,描述依赖相对于导入它的文件的位置。例如,在 JavaScript 中,import 语句或 require 函数可用于创建依赖。在 CSS 中,可以使用 @importurl()。通常,这些依赖不会指定完整的绝对路径,而是指定一个较短的说明符,由 Parcel 和其他工具解析为绝对路径。

¥A dependency specifier is a string that describes the location of a dependency relative to the file that imports it. For example, in JavaScript the import statement or require function may be used to create dependencies. In CSS, @import and url() may be used. Typically, these dependencies do not specify a full absolute path, but rather a shorter specifier that is resolved to an absolute path by Parcel and other tools.

Parcel 实现了 Node 模块解析算法 的增强版本。它负责将依赖说明符转换为可以从文件系统加载的绝对路径。除了许多工具支持的标准依赖说明符之外,Parcel 还支持一些其他说明符类型和功能。

¥Parcel implements an enhanced version of the Node module resolution algorithm. It is responsible for turning a dependency specifier into an absolute path that can be loaded from the file system. In addition to the standard dependency specifiers supported across many tools, Parcel also supports some additional specifier types and features.

相对说明符

#

¥Relative specifiers

相对说明符以 ... 开头,并解析相对于导入文件的文件。

¥Relative specifiers start with . or .., and resolve a file relative to the importing file.

/path/to/project/src/client.js:
import './utils.js';
import '../constants.js';

在上面的示例中,第一次导入将解析为 /path/to/project/src/utils.js,第二次导入将解析为 /path/to/project/constants.js

¥In the above example, the first import would resolve to /path/to/project/src/utils.js and the second would resolve to /path/to/project/constants.js.

文件扩展名

#

¥File extensions

建议在所有导入说明符中包含完整的文件扩展名。这既提高了依赖解析性能,又减少了歧义。

¥It is recommended to include the full file extension in all import specifiers. This both improves dependency resolution performance and reduces ambiguity.

也就是说,为了与 Node 中的 CommonJS 和 TypeScript 兼容,Parcel 允许省略某些文件类型的文件扩展名。可以省略的文件扩展名包括 .ts.tsx.mjs.js.jsx.cjs.json。导入所有其他文件类型需要文件扩展名。

¥That said, for compatibility with CommonJS in Node, and with TypeScript, Parcel allows the file extension to be omitted for certain file types. The file extensions that may be omitted include .ts, .tsx, .mjs, .js, .jsx, .cjs, and .json. A file extension is required to import all other file types.

以下示例解析为与上面相同的文件。

¥The following example resolves to the same files as above.

/path/to/project/src/client.js:
import './utils';
import '../constants';

请注意,只有从 JavaScript 或 TypeScript 文件导入时才可以省略这些。在 HTML 和 CSS 等其他文件类型中定义的依赖始终需要文件扩展名。

¥Note that these may only be omitted when importing from a JavaScript or TypeScript file. File extensions are always required for dependencies defined in other file types like HTML and CSS.

在 TypeScript 文件中,Parcel 还将尝试将 JavaScript 扩展(包括 .js.jsx.mjs.cjs)替换为其 TypeScript 等效项(.ts.tsx.mts.cts)。例如,对 ./foo.js 的依赖将解析为 ./foo.ts。这符合 TSC 的行为。但是,与 TSC 不同的是,如果原始 ./foo.js 存在,则将使用它来代替 TS 版本,这与 Node 和其他打包器的行为相匹配。

¥In TypeScript files, Parcel will also try replacing JavaScript extensions including .js, .jsx, .mjs, and .cjs with their TypeScript equivalents (.ts, .tsx, .mts, and .cts). For example, a dependency on ./foo.js will resolve to ./foo.ts. This matches TSC's behavior. However, unlike TSC, if the original ./foo.js exists, it will be used instead of the TS version, matching the behavior of Node and other bundlers.

目录索引文件

#

¥Directory index files

在 JavaScript、Typescript 和其他基于 JS 的语言中,依赖说明符可能解析为目录而不是文件。如果目录包含 package.json 文件,则将按照 包入口 部分中的说明解析主入口。如果不存在 package.json,它将尝试解析目录中的索引文件,例如 index.jsindex.ts。索引文件支持上面列出的所有扩展名。

¥In JavaScript, Typescript, and other JS-based languages, dependency specifiers may resolve to a directory rather than a file. If the directory contains a package.json file, the main entry will be resolved as described in the Package entries section. If no package.json is present, it will attempt to resolve to an index file within the directory, such as index.js or index.ts. All extensions listed above are supported for index files.

/path/to/project/src/app.js:
import './client';

例如,如果 /path/to/project/src/client 是目录,则上述说明符可以解析为 /path/to/project/src/client/index.js

¥For example, if /path/to/project/src/client were a directory, the above specifier could resolve to /path/to/project/src/client/index.js.

裸说明符

#

¥Bare specifiers

裸说明符以除 ./~# 之外的任何字符开头。在 JavaScript、TypeScript 和其他基于 JS 的语言中,它们解析为 node_modules 中的包。对于其他类型的文件,例如 HTML 和 CSS,裸说明符的处理方式与 相关说明符 相同。

¥Bare specifiers start with any character except ., /, ~, or #. In JavaScript, TypeScript, and other JS-based languages, they resolve to a package in node_modules. For other types of files, such as HTML and CSS, bare specifiers are treated the same way as relative specifiers.

/path/to/project/src/client/index.js:
import 'react';

在上面的示例中,react 可能会解析为 /path/to/project/node_modules/react/index.js 之类的内容。确切的位置取决于 node_modules 目录的位置以及包内的配置。

¥In the above example, react may resolve to something like /path/to/project/node_modules/react/index.js. The exact location will depend on the location of the node_modules directory, as well as configuration within the package.

从导入文件开始向上搜索 node_modules 目录。搜索停止于项目根目录。例如,如果导入文件位于 /path/to/project/src/client/index.js,则将搜索以下位置:

¥node_modules directories are searched upwards from the importing file. The search stops at the project root directory. For example, if the importing file was at /path/to/project/src/client/index.js the following locations would be searched:

一旦找到模块目录,包入口就被解析。有关此过程的更多详细信息,请参阅 包入口

¥Once a module directory is found, the package entry is resolved. See Package entries for more details on this process.

包子路径

#

¥Package sub-paths

裸说明符还可以指定包内的子路径。例如,一个包可能会发布多个入口点,而不是仅发布一个入口点。

¥Bare specifiers may also specify a sub-path within a package. For example, a package may publish multiple entry points rather than only a single one.

import 'lodash/clone';

上面的示例如上所述解析 node_modules 目录中的 lodash,然后解析包中的 clone 模块而不是其主入口点。例如,这可能是 node_modules/lodash/clone.js 文件。

¥The above example resolves lodash within a node_modules directory as described above, and then resolves the clone module within the package rather than its main entrypoint. This could be a node_modules/lodash/clone.js file, for example.

内置模块

#

¥Builtin modules

Parcel 包含许多内置 Node.js 模块的垫片,例如 pathurl。当依赖说明符引用这些模块名称之一时,内置模块优先于 node_modules 中安装的任何同名模块。在构建节点环境时,内置模块不包含在打包包中,否则会包含填充程序。有关内置模块的完整列表,请参阅 Node 文档

¥Parcel includes shims for many builtin Node.js modules, e.g. path and url. When a dependency specifier references one of these module names, the builtin module is preferred over any module installed in node_modules with the same name. When building for a node environment, builtin modules are excluded from the bundle, otherwise a shim is included. See the Node docs for a full list of builtin modules.

在构建 Electron 环境时,electron 模块也被视为内置模块并从打包包中排除。

¥When building for an Electron environment, the electron module is also considered a builtin and excluded from the bundle.

绝对说明符

#

¥Absolute specifiers

绝对说明符以 / 开头,并解析相对于项目根目录的文件。项目根目录是项目的基目录,通常包含包管理器锁定文件(例如 yarn.lockpackage-lock.json)或源代码控制目录(例如 .git)。绝对说明符对于避免深层嵌套层次结构中的相对路径非常长很有用。

¥Absolute specifiers start with /, and resolve a file relative to the project root. The project root is the base directory of your project, which would typically contain a package manager lock file (e.g. yarn.lock or package-lock.json), or a source control directory (e.g. .git). Absolute specifiers could be useful to avoid very long relative paths in deeply nested hierarchies.

import '/src/client.js';

上面的示例可以放置在项目目录结构中任何位置的任何文件中,并且始终解析为 /path/to/project/src/client.js

¥The above example could be placed in any file, at any point in your project’s directory structure, and will always resolve to /path/to/project/src/client.js.

波形符说明符

#

¥Tilde specifiers

波形符说明符以 ~ 开头,并相对于导入文件中最近的包根进行解析。包根目录是一个带有 package.json 文件的目录,通常可以在 node_modules 中找到,或者作为 monorepo 中包的根目录。波形符说明符的用途与绝对说明符类似,但当你有多个包时更有用。

¥Tilde specifiers start with ~, and resolve relative to the nearest package root from the importing file. A package root is a directory with a package.json file, which would typically be found in node_modules, or as the root of a package in a monorepo. Tilde specifiers are useful for similar purposes as absolute specifiers, but are more useful when you have more than one package.

/path/to/project/packages/frontend/src/client/index.js:
import '~/src/utils.js';

上面的示例将解析为 /path/to/project/packages/frontend/src/utils.js

¥The above example would resolve to /path/to/project/packages/frontend/src/utils.js.

哈希说明符

#

¥Hash specifiers

哈希说明符以 # 字符开头,其行为取决于它们所包含的文件类型。在 JavaScript 和 TypeScript 文件中,哈希说明符被视为内部包导入,如下所述。在其他文件中,这些被视为相对 URL 哈希。

¥Hash specifiers start with the # character, and the behavior depends on the file type they are contained within. In JavaScript and TypeScript files, hash specifiers are treated as internal package imports, described below. In other files, these are treated as relative URL hashes.

package.json 中的 "imports" 字段可用于定义适用于包内 JavaScript 或 TypeScript 文件中的导入说明符的私有映射。这允许包根据环境定义条件导入,如 belowNode.js 文档 中所述。

¥The "imports" field in package.json can be used to define private mappings that apply to import specifiers in JavaScript or TypeScript files within the package. This allows a package to define conditional imports depending on the environment, as documented below and in the Node.js docs.

/path/to/project/package.json:
{
"imports": {
"#dep": {
"node": "dep-node",
"browser": "dep-browser"
}
}
}
/path/to/project/src/index.js:
import '#dep';

查询参数

#

¥Query parameters

依赖说明符还可以包括查询参数,这些参数指定已解析文件的转换选项。例如,你可以指定宽度和高度以在加载图片时调整图片大小。

¥Dependency specifiers may also include query parameters, which specify transformation options for the resolved file. For example, you can specify the width and height to resize an image when loading it.

.logo {
background: url(logo.png?width=400&height=400);
}

有关图片的更多详细信息,请参阅 图片转换器 文档。你还可以在自定义 转换器 插件中使用查询参数。

¥See the Image transformer docs for more details on images. You can also use query parameters in custom Transformer plugins.

注意:CommonJS 说明符(由 require 函数创建)不支持查询参数。

¥Note: Query parameters are not supported for CommonJS specifiers (created by the require function).

URL 方案

#

¥URL schemes

依赖说明符可以使用 URL 方案来定位 命名管道。这些允许你指定与默认管道不同的管道来编译文件。例如,bundle-text: 方案可用于将已编译的包内联为文本。详细信息请参见 打包内联

¥Dependency specifiers may use URL schemes to target Named pipelines. These allow you to specify a different pipeline to compile a file with than the default one. For example, the bundle-text: scheme can be used to inline a compiled bundle as text. See Bundle inlining for more details.

有一些保留的 URL 方案可能无法用于命名管道,但具有内置行为。

¥There are a few reserved URL schemes that may not be used for named pipelines, and have builtin behavior.

通配说明符

#

¥Glob specifiers

Parcel 支持通过 glob 一次导入多个文件,但是,由于 glob 导入是非标准的,因此它们不包含在默认的 Parcel 配置中。要启用它们,请将 @parcel/resolver-glob 添加到 .parcelrc

¥Parcel supports importing multiple files at once via globs, however, since glob imports are non-standard, they are not included in the default Parcel config. To enable them, add @parcel/resolver-glob to your .parcelrc.

.parcelrc:
{
"extends": "@parcel/config-default",
"resolvers": ["@parcel/resolver-glob", "..."]
}

启用后,你可以使用 ./files/*.js 等说明符导入多个文件。这将返回一个对象,其键对应于文件名。

¥Once enabled, you can import multiple files using a specifier like ./files/*.js. This returns an object with keys corresponding to the files names.

import * as files from './files/*.js';

相当于:

¥is equivalent to:

import * as foo from './files/foo.js';
import * as bar from './files/bar.js';

let files = {
foo,
bar
};

具体来说,通配符模式的动态部分成为对象的键。如果有多个动态部分,将返回一个嵌套对象。例如,如果存在 pages/profile/index.js 文件,则以下内容将与其匹配。

¥Specifically, the dynamic parts of the glob pattern become keys of the object. If there are multiple dynamic parts, a nested object will be returned. For example, if a pages/profile/index.js file existed, the following would match it.

import * as pages from './pages/*/*.js';

console.log(pages.profile.index);

这也适用于 bundle-text: 等 URL 方案以及动态导入。使用动态导入时,生成的对象将包含文件名到函数的映射。可以调用每个函数来加载已解析的模块。这意味着每个文件都是按需加载的,而不是全部预先加载。

¥This also works with URL schemes like bundle-text:, as well as with dynamic import. When using dynamic import, the resulting object will include a mapping of filenames to functions. Each function can be called to load the resolved module. This means that each file is loaded on demand rather than all up-front.

let files = import('./files/*.js');

async function doSomething() {
let foo = await files.foo();
let bar = await files.bar();
return foo + bar;
}

Glob 还可以用于从 npm 包导入文件:

¥Globs may also be used to import files from npm packages:

import * as locales from '@company/pkg/i18n/*.js';

console.log(locales.en.message);

Glob 导入也适用于 CSS:

¥Glob imports also work with CSS:

@import "./components/*.css";

相当于:

¥is equivalent to:

@import "./components/button.css";
@import "./components/dropdown.css";

包入口

#

¥Package entries

解析包目录时,将参考 package.json 文件来确定包入口。Parcel 检查以下字段(按顺序):

¥When resolving a package directory, the package.json file is consulted to determine the package entry. Parcel checks the following fields (in order):

如果这些字段均未设置,或者它们指向的文件不存在,则解析将回退到索引文件。详细信息请参见 目录索引文件

¥If none of these fields are set, or the files they point to do not exist, then resolution falls back to an index file. See Directory index files for more details.

包导出

#

¥Package exports

package.json 中的 "exports" 字段可用于定义包的可公开访问的入口点。这些还可以根据环境定义条件行为,允许解析根据模块导入位置(例如节点或浏览器)而改变。

¥The "exports" field in package.json can be used to define the publically accessible entrypoints for a package. These can also define conditional behavior based on the environment, allowing resolution to change depending on where a module is imported from (e.g. node or browser).

启用包导出

#

¥Enabling package exports

默认情况下,包导出是禁用的,因为它们可能会破坏未考虑到它们的现有项目。你可以通过将以下内容添加到项目根目录中的 package.json 文件来启用支持。

¥Package exports are disabled by default because they may break existing projects that weren't designed with them in mind. You can enable support by adding the following to the package.json file in your project root directory.

/path/to/project/package.json:
{
"@parcel/resolver-default": {
"packageExports": true
}
}

单次导出

#

¥Single export

如果包只有一个导出模块,则 "exports" 字段可以定义为字符串:

¥If a package has only a single exported module, the "exports" field may be defined as a string:

package.json:
{
"name": "foo",
"exports": "./dist/index.js"
}

当用户导入上例中的 "foo" 包时,node_modules/foo/dist/index.js 模块将被解析。

¥When a user imports the "foo" package in the above example, the node_modules/foo/dist/index.js module will be resolved.

多次导出

#

¥Multiple exports

如果一个包导出多个模块,则 "exports" 字段可以提供定义在何处查找每个导出的映射。"." 导出定义主入口点,其他入口定义为子路径。

¥If a package exports multiple modules, the "exports" field can provide mappings defining where to find each of these exports. The "." export defines the main entry point, and other entries are defined as subpaths.

package.json:
{
"name": "foo",
"exports": {
".": "./dist/index.js",
"./bar": "./dist/bar.js"
}
}

使用上述包,用户可以导入 "foo"(解析为 node_modules/foo/dist/index.js)或 "foo/bar"(解析为 node_modules/foo/dist/bar.js)。

¥With the above package, a user may import "foo", which resolves to node_modules/foo/dist/index.js, or "foo/bar", which resolves to node_modules/foo/dist/bar.js.

任何未由包含 "exports" 字段的包显式导出的子路径将无法被使用者访问。例如,尝试在上述包中导入 "foo/abc" 将导致构建时错误。

¥Any subpath that is not explicitly exported by a package containing the "exports" field will not be accessible by a consumer. For example, attempting to import "foo/abc" in the above package would result in a build time error.

* 字符可以在导出映射中用作通配符。映射的左侧只能出现一个 *,匹配的字符串将被替换到右侧的每个实例中。这使你可以避免手动列出要导出的每个文件。

¥The * character may be used within an exports mapping as a wildcard. Only one * may appear in the lefthand side of the mapping, and the matched string is replaced into each instance in the righthand side. This allows you to avoid manually listing every file you want to export.

package.json:
{
"name": "foo",
"exports": {
"./*": "./dist/*.js"
}
}

在上面的示例中,dist 目录中的所有 .js 文件均从包中导出,不带扩展名。例如,导入 "foo/bar" 将解析为 node_modules/foo/dist/bar.js

¥In the above example, all .js files in the dist directory are exported from the package, without their extension. For example, importing "foo/bar" would resolve to node_modules/foo/dist/bar.js.

条件导出

#

¥Conditional exports

"exports" 字段还可以在不同的 environments 或其他条件下为相同的说明符定义不同的映射。例如,一个包可以为 ES 模块和 CommonJS,或者为 Node 和浏览器提供不同的入口点。

¥The "exports" field may also define different mappings for the same specifier in different environments or other conditions. For example, a package may provide different entrypoints for ES modules and CommonJS, or for Node and browsers.

package.json:
{
"name": "foo",
"exports": {
"node": "./dist/node.js",
"default": "./dist/default.js"
}
}

在上面的例子中,如果消费者从 Node 环境导入 "foo" 模块,它将解析为 node_modules/foo/dist/node.js,否则它将解析为 node_modules/foo/default.js

¥In the above example, if a consumer imports the "foo" module from a Node environment, it will resolve to node_modules/foo/dist/node.js, otherwise it will resolve to node_modules/foo/default.js.

条件导出也可以嵌套在子路径映射中。

¥Conditional exports may also be nested within subpath mappings.

package.json:
{
"name": "foo",
"exports": {
"./bar": {
"node": "./dist/bar-node.js",
"default": "./dist/bar-default.js"
}
}
}

这允许导入 "foo/bar" 以解析为 Node 和其他环境的不同文件。

¥This allows importing "foo/bar" to resolve to a different file for Node and other environments.

条件导出也可以相互嵌套以创建更复杂的逻辑。

¥Conditional exports may also be nested within each other to create more complex logic.

package.json:
{
"name": "foo",
"exports": {
"node": {
"import": "./dist/node.mjs",
"require": "./dist/node.cjs"
},
"default": "./dist/default.js"
}
}

上面的示例定义了模块的不同版本,具体取决于包是通过 Node 环境中的 ESM import 还是 CommonJS require 加载。

¥The above example defines different versions of the module depending on whether the package is loaded via ESM import or CommonJS require within a Node environment.

Parcel 支持以下导出条件:

¥Parcel supports the following exports conditions:

导出条件的解析顺序遵循它们在 package.json 中定义的顺序,而不是上面列出的顺序。

¥The order that exports conditions are resolved follows the order they are defined in the package.json, not the order they are listed above.

更多示例

#

¥More examples

有关 package.json 导出的更多详细信息,请参阅 Node.js 文档

¥For more details about package.json exports, see the Node.js documentation.

别名

#

¥Aliases

别名可用于覆盖依赖的正常解析。例如,你可能想要使用不同但与 API 兼容的替换来覆盖模块,或者将依赖映射到从 CDN 加载的库定义的全局变量。

¥An alias can be used to override the normal resolution of a dependency. For example, you may want to override a module with a different but API-compatible replacement, or map a dependency to a global variable defined by a library loaded from a CDN.

别名是通过 package.json 中的 alias 字段定义的。它们可以在距离包含依赖的源文件最近的 package.json 中本地定义,也可以在项目根目录的 package.json 中全局定义。全局别名适用于项目中的所有文件和包,包括 node_modules 中的文件和包。

¥Aliases are defined via the alias field in package.json. They can be defined either locally in the nearest package.json to the source file containing the dependency, or globally in the package.json in the project root directory. Global aliases apply to all files and packages in the project, including those in node_modules.

包别名

#

¥Package aliases

包别名将 node_modules 依赖映射到不同的包或项目中的本地文件。例如,要在项目中的两个文件以及 node_modules 中的任何其他库中将 reactreact-dom 替换为 Preact,你可以在项目根目录中的 package.json 中定义一个全局别名。

¥Package aliases map a node_modules dependency to a different package, or to a local file within your project. For example, to replace react and react-dom with Preact across both files in your project as well as any other libraries in node_modules, you could define a global alias in the package.json in your project root directory.

package.json:
{
"alias": {
"react": "preact/compat",
"react-dom": "preact/compat"
}
}

你还可以使用定义别名的 package.json 中的相对路径将模块映射到项目中的文件。

¥You can also map a module to a file within your project by using a relative path from the package.json in which the alias is defined.

package.json:
{
"alias": {
"react": "./my-react.js"
}
}

还支持仅对模块的某些 sub-paths 进行别名。此示例将 lodash/clone 别名为 tiny-clonelodash 包中的其他导入将不受影响。

¥Aliasing only certain sub-paths of a module is also supported. This example will alias lodash/clone to tiny-clone. Other imports within the lodash package will be unaffected.

package.json:
{
"alias": {
"lodash/clone": "tiny-clone"
}
}

这也以另一种方式起作用:如果整个模块有别名,则该包的任何子路径导入都将在别名模块内解析。例如,如果你将 lodash 别名为 my-lodash 并导入 lodash/clone,则这将解析为 my-lodash/clone

¥This also works the other way: if an entire module is aliased, then any sub-path imports of that package will be resolved within the aliased module. For example, if you aliased lodash to my-lodash and imported lodash/clone, this would resolve to my-lodash/clone.

文件别名

#

¥File aliases

别名还可以定义为相对路径,以用不同的文件替换包中的特定文件。可以使用 alias 字段无条件替换文件,或者使用 sourcebrowser 字段有条件替换文件。有关这些字段的详细信息,请参阅上面的 包入口

¥Aliases can also be defined as relative paths to replace a specific file within a package with a different file. This can be done using the alias field to replace the file unconditionally, or with the source or browser fields to do conditionally. See Package entries above for details about these fields.

例如,要将某个文件替换为特定于浏览器的版本,你可以使用 browser 字段。

¥For example, to replace a certain file with a browser-specific version, you could use the browser field.

package.json:
{
"browser": {
"./fs.js": "./fs-browser.js"
}
}

现在,如果在浏览器环境中导入 my-module/fs.js,他们实际上会得到 my-module/fs-browser.js。这既适用于从外部(例如 包子路径)导入,也适用于模块内部的导入。

¥Now, if my-module/fs.js is imported in a browser environment, they'll actually get my-module/fs-browser.js. This applies both to imports from outside (e.g. package sub-paths), as well as internally within the module.

全局别名

#

¥Glob aliases

文件别名也可以使用 glob 来定义,这允许使用单个模式替换许多文件。替换可以包括诸如 $1 之类的模式来访问捕获的全局匹配。可以使用 alias 字段无条件替换文件,或使用 sourcebrowser 字段有条件替换文件。有关这些字段的详细信息,请参阅上面的 包入口

¥File aliases can also be defined using globs, which allows replacing many files using a single pattern. The replacement can include patterns such as $1 to access the captured glob matches. This can be done using the alias field to replace files unconditionally, or with the source or browser fields to do conditionally. See Package entries above for details about these fields.

例如,你可以使用 source 字段提供包中已编译代码与原始源代码之间的映射。当模块被符号链接或在 monorepo 中时,这将允许 Parcel 从源代码编译模块,而不是使用预编译的版本。

¥For example, you could use the source field to provide a mapping between compiled code in a package and the original source code. When the module is symlinked, or within a monorepo, this will allow Parcel to compile the module from source rather than use the pre-compiled version.

package.json:
{
"source": {
"./dist/*": "./src/$1"
}
}

现在,每当导入 dist 目录中的文件时,都会加载 src 文件夹中的相应文件。

¥Now, any time a file in the dist directory is imported, the corresponding file in the src folder will be loaded instead.

垫片别名

#

¥Shim aliases

文件或包可以别名为 false 以从构建中排除,并替换为空模块。例如,这对于从浏览器版本中排除某些仅在 Node.js 中运行的模块很有用。

¥Files or packages can be aliased to false to be excluded from the build, and replaced with an empty module. This could be useful to exclude certain modules from browser builds that only work in Node.js, for example.

package.json:
{
"alias": {
"fs": false
}
}

全局别名

#

¥Global aliases

文件或包也可以别名为将在运行时定义的全局变量。例如,可以从 CDN 加载特定库。任何时候解决对该库的依赖时,它都将被替换为对该全局变量的引用,而不是打包它,而不是打包它。

¥Files or packages may also be aliased to global variables that will be defined at runtime. For example, a particular library may be loaded from a CDN. Rather than bundling it, any time a dependency on that library is resolved, it will be replaced with a reference to that global variable instead of being bundled.

这可以通过为具有 global 属性的对象创建别名来完成。以下示例将 jquery 依赖说明符别名为全局变量 $

¥This can be done by creating an alias to an object with a global property. The following example aliases the jquery dependency specifier to the global variable $.

package.json:
{
"alias": {
"jquery": {
"global": "$"
}
}
}

TSConfig

#

Parcel 支持 TypeScript 的 tsconfig.json 配置文件中定义的一些设置,包括 baseUrlpathsmoduleSuffixes。Parcel 从包含依赖的文件向上搜索,找到最近的 tsconfig.json 文件。它还支持使用 extends 选项将多个 tsconfig 的设置合并在一起。有关详细信息,请参阅 TypeScript 文档

¥Parcel supports some settings defined in TypeScript's tsconfig.json config file, including baseUrl, paths, and moduleSuffixes. Parcel searches upward from the file containing the dependency to find the nearest tsconfig.json file. It also supports using the extends option to merge the settings from multiple tsconfigs together. See the TypeScript docs for more details.

baseUrl

#

baseUrl 字段定义从中解析 裸说明符 的基目录。

¥The baseUrl field defines the base directory from which to resolve bare specifiers.

tsconfig.json:
{
"compilerOptions": {
"baseUrl": "./src"
}
}
src/App.js:
import 'Home';

在上面的示例中,Home 将解析为 src/Home.js(如果存在)。否则,它将回退到 node_modules/Home,例如。

¥In the above example, Home will resolve to src/Home.js if it exists. Otherwise, it will fall back to node_modules/Home, for example.

paths

#

paths 字段可用于定义从 裸说明符 到文件路径的映射。你还可以使用 * 字符定义通配符模式。

¥The paths field can be used to define mappings from bare specifiers to file paths. You can also define wildcard patterns using the * character.

paths 字段中引用的文件路径相对于 baseUrl(如果已定义),否则相对于包含 tsconfig.json 文件的目录。

¥File paths referenced in the paths field are relative to the baseUrl if defined, otherwise to the directory containing the tsconfig.json file.

tsconfig.json:
{
"compilerOptions": {
"paths": {
"jquery": ["./vendor/jquery/dist/jquery"],
"app/*": ["./src/app/*"]
}
}
}
src/App.js:
import 'jquery';
import 'app/foo';

在上面的示例中,jquery 解析为 ./vendor/jquery/dist/jquery.jsapp/foo 解析为 ./src/app/foo.js

¥In the above example, jquery resolves to ./vendor/jquery/dist/jquery.js, and app/foo resolves to ./src/app/foo.js.

moduleSuffixes

#

moduleSuffixes 字段允许你指定解析模块时要搜索的文件名后缀。

¥The moduleSuffixes field allows you to specify the file name suffixes to search for when resolving a module.

tsconfig.json:
{
"compilerOptions": {
"moduleSuffixes": [".ios", ".native", ""]
}
}
src/App.js:
import './foo';

在上面的示例中,Parcel 将查找 ./foo.ios.ts./foo.native.ts./foo.ts(以及 .tsx.js 等其他扩展名)。

¥In the above example, Parcel will look for ./foo.ios.ts, ./foo.native.ts, and ./foo.ts (in addition to other extensions like .tsx, .js, etc.).

配置其他工具

#

¥Configuring other tools

本节介绍如何配置其他工具以与 Parcel 的节点解析算法扩展一起使用。

¥This section covers how to configure other tools to work with Parcel’s extensions to the Node resolution algorithm.

TypeScript

#

TypeScript 需要配置为支持 Parcel 功能,例如绝对和波形符依赖说明符以及别名。这可以使用 tsconfig.json 中的 paths 选项来完成。请参阅 TypeScript 模块解析文档 了解更多信息。

¥TypeScript will need to be configured to support Parcel features like absolute and tilde dependency specifiers, and aliases. This can be done using the paths option in tsconfig.json. See the TypeScript Module Resolution docs for more information.

例如,要将波浪号路径映射到根目录,可以使用以下配置:

¥For example, to map tilde paths to the root directory, this configuration could be used:

tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~*": ["./*"]
}
}
}

还可以通过在项目中创建 环境模块 声明来启用对 URL 方案 的支持。例如,要将使用 bundle-text: 方案加载的依赖映射到字符串,你可以使用以下声明。可以将其放置在项目中任何位置的文件中,例如 parcel.d.ts

¥Support for URL schemes can also be enabled by creating an ambient module declaration in your project. For example, to map dependencies loaded with the bundle-text: scheme to a string, you could use the following declaration. This can be placed in a file such as parcel.d.ts anywhere in your project.

parcel.d.ts:
declare module 'bundle-text:*' {
const value: string;
export default value;
}

Flow

#

需要配置 Flow 以支持绝对和波形符说明符以及别名。这可以使用 .flowconfig 中的 module.name_mapper 功能来完成。

¥Flow needs to be configured to support absolute and tilde specifiers, and aliases. This can be done using the module.name_mapper feature in your .flowconfig.

例如,要映射绝对说明符以从项目根解析,可以使用以下配置:

¥For example, to map absolute specifiers to resolve from the project root, this configuration could be used:

.flowconfig:
[options]
module.name_mapper='^\/\(.*\)$' -> '<PROJECT_ROOT>/\1'

要启用 URL 方案,你需要创建到 .flow 声明文件 的映射,以导出预期类型。例如,要将使用 bundle-text: 方案加载的依赖映射到字符串,你可以创建一个名为 bundle-text.js.flow 的文件,并将引用该方案的所有依赖映射到它。

¥To enable URL schemes, you'll need to create a mapping to a .flow declaration file which exports the expected type. For example, to map dependencies loaded with the bundle-text: scheme to a string, you could create a file called bundle-text.js.flow and map all dependencies referencing the scheme to it.

bundle-text.js.flow:
// @flow
declare var value: string;
export default value;
.flowconfig:
[options]
module.name_mapper='^bundle-text:.*$' -> '<PROJECT_ROOT>/bundle-text.js'
Parcel 中文网 - 粤ICP备13048890号