require-passing-this
✅ recommended を使用した場合、このルールが有効になります。
🔧 このルールによってエラーになるコードは ESLint の --fix コマンド で自動修正できます。
このルールは Construct のコンストラクタに this を渡すことを強制します。
AWS CDK リソースを作成するとき、Construct に this を渡すことは正しいリソース階層を維持するために重要です。
Construct のコンストラクタの第一引数へ this 以外の値 (特に、親コンストラクタから受け取った scope 変数など) を渡してしまうと、次のような問題が発生する可能性があります
- 生成される CloudFormation テンプレートのリソース階層が正しくない
- 予期しないリソースの命名
(このルールは Construct から派生したクラスにのみ適用されます)
🔧 使用方法
js
// eslint.config.mjs
export default defineConfig([
{
// ... some configs
rules: {
"cdk/require-passing-this": "error",
},
},
]);✅ 正しい例
ts
import { Construct } from "constructs";
import { Bucket } from "aws-cdk-lib/aws-s3";
export class MyConstruct extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);
const sample = new SampleConstruct(this, "Sample");
// ✅ `this` は常に使用できます
new Bucket(this, "SampleBucket");
// ✅ `sample` (Construct のインスタンス) をスコープとして渡すことが許可される
new OtherConstruct(sample, "Child");
}
}❌ 不正な例
ts
import { Construct } from "constructs";
import { Bucket } from "aws-cdk-lib/aws-s3";
export class MyConstruct extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);
// ❌ scope を使用すべきではありません
new Bucket(scope, "SampleBucket");
}
}オプション
ts
type Options = {
allowNonThisAndDisallowScope: boolean;
};
const defaultOptions: Options = {
allowNonThisAndDisallowScope: true,
};allowNonThisAndDisallowScope
Construct のコンストラクタの第一引数 (スコープ) として、this 以外の値を許可するかどうかを決定します。
false: 新しい Construct をインスタンス化する際、第一引数 (スコープ) としてthisのみが許可されますtrue:this以外の Construct インスタンスを第一引数 (スコープ) として渡すことを許可します- ただし、親コンストラクタが受け取った
scope変数を直接使用することは引き続き禁止されます - この設定は、ネストされた Construct 階層を作成する場合に便利です。
- ただし、親コンストラクタが受け取った
✅ Correct Example
ts
import { Construct } from "constructs";
import { Bucket } from "aws-cdk-lib/aws-s3";
export class MyConstruct extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);
// ✅ `this` は常に使用できます
new Bucket(this, "SampleBucket");
}
}❌ Incorrect Example
ts
import { Construct } from "constructs";
import { Bucket } from "aws-cdk-lib/aws-s3";
export class MyConstruct extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);
const sample = new SampleConstruct(this, "Sample");
// ❌ scope を使用すべきではありません、
new Bucket(scope, "SampleBucket");
// ❌ 他の Construct インスタンスをスコープとして使用すべきではありません。
new OtherConstruct(sample, "Child");
}
}