Skip to content

require-passing-this

recommended を使用した場合、このルールが有効になります。
🔧 このルールによってエラーになるコードは ESLint の --fix コマンド で自動修正できます。

このルールは CDK Construct のコンストラクタの第一引数に this を渡すことを強制します。

AWS CDK リソースを作成するとき、Construct に this を渡すことは正しいリソース階層を維持するために重要です。

Construct のコンストラクタの第一引数へ this 以外の値 (特に、親コンストラクタから受け取った scope 変数など) を渡してしまうと、次のような問題が発生する可能性があります

  • 生成される CloudFormation テンプレートのリソース階層が正しくない
  • 予期しないリソースの命名

🔧 使用方法

js
// eslint.config.mjs
export default defineConfig([
  {
    // ... some configs
    rules: {
      "awscdk/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");

    // ✅ 他の Construct インスタンス (この場合は sample) をスコープとして指定できる
    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 のコンストラクタの第一引数 (scope) として、this 以外の値を許可するかどうかを決定します。

  • false: 新しい Construct をインスタンス化する際、第一引数 (scope) として this のみが許可されます
  • true: this 以外の Construct インスタンスを第一引数 (scope) として渡すことを許可します
    • ただし、親コンストラクタが受け取った 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 インスタンス (この場合は sample) をスコープとして指定している
    new OtherConstruct(sample, "Child");
  }
}