0
votes

I am having an issue with creating an CloudFrontWebDistribution object with aws-cdk v1.7. The compiler doesn't seem to be happy about the construct I passed in.

import { Stack, StackProps, Construct, App } from '@aws-cdk/core';
import { CloudFrontWebDistribution } from '@aws-cdk/aws-cloudfront';

export class MyCloudFrontStack extends Stack {

    constructor(scope: Construct, id: string, CloudFrontStackParameters, props?: StackProps) {
        super(scope, id, props);

        const env = parameters.environment.toLowerCase();
        const webDistributionConfigs = { // configurations here... };
        this.cloudFrontWebDistrubtion = new CloudFrontWebDistribution(scope, id, webDistributionConfigs); // typescript complaining about the scope variable
    }
}

The typescript compiler then complains about the scope variable passed into the CloudFrontWebDistribution constructor.

Argument of type 'import("c:/Users/me/node_modules/@aws-cdk/core/lib/construct").Construct' is not assignable to parameter of type 'import("c:/Users/me/node_modules/@aws-cdk/aws-lambda/node_modules/@aws-cdk/core/lib/construct").Construct'. Types of property 'node' are incompatible. Property '_defaultChild' is missing in type 'import("c:/Users/me/node_modules/@aws-cdk/core/lib/construct").ConstructNode' but required in type 'import("c:/Users/me/node_modules/@aws-cdk/aws-lambda/node_modules/@aws-cdk/core/lib/construct").ConstructNode'.ts(2345) construct.d.ts(61, 13): '_defaultChild' is declared here.

Is it because I use the type incorrectly here? Any ideas what I have done wrong?

1
Can you confirm that all your @aws-cdk/... deps are using v1.7.0? - jogold

1 Answers

0
votes

Here's what I did to fix this issue.

import { Stack, StackProps, Construct, App } from '@aws-cdk/core';
import { CloudFrontWebDistribution } from '@aws-cdk/aws-cloudfront';

export class MyCloudFrontStack extends Stack {

    constructor(scope: Construct, id: string, CloudFrontStackParameters, props?: StackProps) {
        super(scope, id, props);

        const env = parameters.environment.toLowerCase();
        const webDistributionConfigs = { // configurations here... };
        this.cloudFrontWebDistrubtion = new CloudFrontWebDistribution(this, id, webDistributionConfigs); 
    }
}

The key here is to use this keyword and pass it in as the first argument in the new CloudFrontWebDistribution(...) constructor. I think this is to tell the CDK to create the CloudFront web distribution for the current stack only, i.e. MyCloudFrontStack, not the parent stack (the scope variable).

Also, by explicitly adding dependencies in package.json and making sure they are on the same version, it'd help avoid possible version conflicts for packages.