@cdklabs/deploy-time-build

中文文档
0.1.16发布于 2026/11/04Apache-2.0TypeScriptCommonJS零依赖构建来源已验证近 30 天下载 3.9万

Run build on CDK deployment time.

原始使用文档
文档目录5 节
  1. Usage
  2. Build Node.js apps
  3. Build a container image
  4. Build SOCI index for a container image
  5. Development

Deploy-time Build

AWS CDK L3 construct that allows you to run a build job for specific purposes. Currently this library supports the following use cases:

  • Build web frontend static files
  • Build a container image
  • Build Seekable OCI (SOCI) indices for container images

View on Construct Hub

Usage

Install from npm:

npm i @cdklabs/deploy-time-build

This library defines several L3 constructs for specific use cases. Here is the usage for each case.

Build Node.js apps

You can build a Node.js app such as a React frontend app on deploy time by the NodejsBuild construct.

architecture

The following code is an example to use the construct:

import { NodejsBuild } from '@cdklabs/deploy-time-build';

new NodejsBuild(this, 'ExampleBuild', {
    assets: [
        {
            path: 'example-app',
            exclude: ['dist', 'node_modules'],
        },
    ],
    destinationBucket,
    distribution,
    outputSourceDirectory: 'dist',
    buildCommands: ['npm ci', 'npm run build'],
    buildEnvironment: {
        VITE_API_ENDPOINT: api.url,
    },
    nodejsVersion: 24,
});

Note that it is possible to pass environment variable VITE_API_ENDPOINT: api.url to the construct, which is resolved on deploy time, and injected to the build environment (a vite process in this case.) The resulting build artifacts will be deployed to destinationBucket from CodeBuild.

You can specify multiple input assets by assets property. These assets are extracted to respective sub directories. For example, assume you specified assets like the following:

new NodejsBuild(this, 'ExampleBuild', {
    assets: [
        {
            // directory containing source code and package.json
            path: 'example-app',
            exclude: ['dist', 'node_modules'],
            commands: ['npm install'],
        },
        {
            // directory that is also required for the build
            path: 'module1',
        },
    ],
    destinationBucket,
    distribution,
    outputSourceDirectory: 'dist',
    nodejsVersion: 24,
});

Then, the extracted directories will be located as the following:

.                         # a temporary directory (automatically created)
├── example-app           # extracted example-app assets
│   ├── src/              # dist or node_modules directories are excluded even if they exist locally.
│   ├── package.json      # npm install will be executed since its specified in `commands` property.
│   └── package-lock.json
└── module1               # extracted module1 assets

You can also override the path where assets are extracted by extractPath property for each asset.

With outputEnvFile property enabled, a .env file is automatically generated and uploaded to your S3 bucket. This file can be used running you frontend project locally. You can download the file to your local machine by running the command added in the stack output.

Please also check the example directory for a complete example.

Allowing access from the build environment to other AWS resources

Since NodejsBuild construct implements iam.IGrantable interface, you can use grant* method of other constructs to allow access from the build environment.

declare const someBucket: s3.IBucket;
declare const build: NodejsBuild;
someBucket.grantReadWrite(build);

You can also use iam.Grant class to allow any actions and resources.

declare const build: NodejsBuild;
iam.Grant.addToPrincipal({ grantee: build, actions: ['s3:ListBucket'], resourceArns:['*'] })

Motivation - why do we need the NodejsBuild construct?

I talked about why this construct can be useful in some situations at CDK Day 2023. See the recording or slides below:

Recording | Slides

Caching

You can enable npm caching to speed up builds using the cache property:

new NodejsBuild(this, 'ExampleBuild', {
    assets: [
        {
            path: 'example-app',
            exclude: ['dist', 'node_modules'],
        },
    ],
    destinationBucket,
    outputSourceDirectory: 'dist',
    cache: CacheType.S3, // or CacheType.LOCAL
    nodejsVersion: 24,
});

Two cache types are available:

  • CacheType.S3: Stores the npm cache directory in an S3 bucket. Good for builds that run infrequently on different hosts.
  • CacheType.LOCAL: Stores the npm cache directory on the build host. Faster than S3 but only effective if builds run on the same host.

Compute Type

You can specify the compute type for the CodeBuild project using the computeType property:

new NodejsBuild(this, 'ExampleBuild', {
    assets: [
        {
            path: 'example-app',
            exclude: ['dist', 'node_modules'],
        },
    ],
    destinationBucket,
    outputSourceDirectory: 'dist',
    computeType: ComputeType.MEDIUM,
    nodejsVersion: 24,
});

Considerations

Since this construct builds your frontend apps every time you deploy the stack and there is any change in input assets (and currently there's even no build cache in the Lambda function!), the time a deployment takes tends to be longer (e.g. a few minutes even for the simple app in example directory.) This might results in worse developer experience if you want to deploy changes frequently (imagine cdk watch deployment always re-build your frontend app).

To mitigate this issue, you can separate the stack for frontend construct from other stacks especially for a dev environment. Another solution would be to set a fixed string as an asset hash, and avoid builds on every deployment.

new NodejsBuild(this, 'ExampleBuild', {
    assets: [
        {
            path: '../frontend',
            exclude: ['node_modules', 'dist'],
            commands: ['npm ci'],
            // Set a fixed string as a asset hash to prevent deploying changes.
            // This can be useful for an environment you use to develop locally.
            assetHash: 'frontend_asset',
        },
    ],
    destinationBucket,
    distribution,
    outputSourceDirectory: 'dist',
    nodejsVersion: 24,
});

Build a container image

You can build a container image at deploy time by the following code:

import { ContainerImageBuild } from '@cdklabs/deploy-time-build';

const image = new ContainerImageBuild(this, 'Build', { 
    directory: 'example-image', 
    buildArgs: { DUMMY_FILE_SIZE_MB: '15' },
    tag: 'my-image-tag',
});
new DockerImageFunction(this, 'Function', {
    code: image.toLambdaDockerImageCode(),
});
const armImage = new ContainerImageBuild(this, 'BuildArm', {
    directory: 'example-image',
    platform: Platform.LINUX_ARM64,
    repository: image.repository,
    zstdCompression: true,
});
new FargateTaskDefinition(this, 'TaskDefinition', { 
    runtimePlatform: { cpuArchitecture: CpuArchitecture.ARM64 } 
}).addContainer('main', {
    image: armImage.toEcsDockerImageCode(),
});

The third argument (props) are a superset of DockerImageAsset's properties. You can set a few additional properties such as tag, repository, and zstdCompression.

Build SOCI index for a container image

Seekable OCI (SOCI) is a way to help start tasks faster for Amazon ECS tasks on Fargate 1.4.0. You can build and push a SOCI index using the SociIndexV2Build construct.

soci-architecture

The following code is an example to use the construct:

import { SociIndexV2Build } from '@cdklabs/deploy-time-build';

const asset = new DockerImageAsset(this, 'Image', { directory: 'example-image' });
const sociIndex = new SociIndexV2Build(this, 'SociV2Index', {
  repository: asset.repository,
  inputImageTag: asset.assetHash,
  outputImageTag: `${asset.assetHash}-soci`,
});

// Use with ECS Fargate
const taskDefinition = new FargateTaskDefinition(this, 'TaskDefinition');
taskDefinition.addContainer('main', {
  image: sociIndex.toEcsDockerImageCode(),
});

// Or create from DockerImageAsset using utility method
const sociIndexFromAsset = SociIndexV2Build.fromDockerImageAsset(this, 'SociV2Index2', asset);

The SociIndexV2Build construct:

  • Takes an input container image and builds a SOCI v2 index for it
  • Outputs a new image tag with the embedded SOCI index
  • Provides toEcsDockerImageCode() method to easily use with ECS tasks
  • Uses the same ECR repository for input and output images

We currently use soci-wrapper to build and push SOCI indices.

[!WARNING] The previous SocideIndexBuild construct is now deprecated. Customers new to SOCI on AWS Fargate can only use SOCI index manifest v2. See this article for more details.

Motivation - why do we need the SociIndexBuild construct?

Currently there are several other ways to build a SOCI index; 1. use soci-snapshotter CLI, or 2. use cfn-ecr-aws-soci-index-builder solution, none of which can be directly used from AWS CDK. If you are familiar with CDK, you should often deploy container images as CDK assets, which is an ideal way to integrate with other L2 constructs such as ECS. To make the developer experience for SOCI as close as the ordinary container images, the SociIndexBuild allows you to deploying a SOCI index directly from CDK, without any dependencies outside of CDK context.

Development

Commands for maintainers:

# run test locally
npx tsc -p tsconfig.dev.json
npx integ-runner
npx integ-runner --update-on-failed

版本与发布记录

@cdklabs/deploy-time-build 共发布 27 个版本,首次发布于 2026/01/16;过去 12 个月发布了 27 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.16latest2026/11/045 天前
0.1.152026/11/018 天前
0.1.142026/10/2614 天前
0.1.132026/10/2614 天前
0.1.122026/10/2614 天前
0.1.112026/10/011 个月前

关于 @cdklabs/deploy-time-build 的常见问题

@cdklabs/deploy-time-build 是什么?

Run build on CDK deployment time.

如何安装 @cdklabs/deploy-time-build?

在项目目录运行 npm install @cdklabs/deploy-time-build,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:constructs(^10.5.1)、aws-cdk-lib(^2.38.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@cdklabs/deploy-time-build 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cdklabs/deploy-time-build 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@cdklabs/deploy-time-build 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 18.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cdklabs/deploy-time-build 可以商用吗?

@cdklabs/deploy-time-build 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@cdklabs/deploy-time-build 的下载量有多少?

根据 npm 官方下载统计,@cdklabs/deploy-time-build 在 2026/10/10 – 2026/11/08 这 30 天内被下载 39,497 次,日均约 1,317 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cdklabs/deploy-time-build 还在维护吗?

最新版本 0.1.16 发布于 2026/11/04(5 天前);至今共发布 27 个版本,其中过去 12 个月发布了 27 个;首次发布于 2026/01/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。