'Go project containing Typescript AWS-CDK directory has cluttered go.mod file

I have a Go project containing a Typescript AWS-CDK directory to define the Stack that contains the Go binary.

The simplest project for this example is:

mkdir example
cd example
mkdir infrastructure
cd infrastructure
cdk init app --language typescript
cd ..
go mod init example
go mod tidy

At this point, go.mod is full of aws-cdk-go references (despite the fact I'm using Typescript). Ideally, go.mod shouldn't have any dependencies at this point. It appears that there are several Go files buried in the node_modules/aws-cdk/.... path that may be influencing go mod tidy.

I'm not yet interested in using the Go CDK libraries. Besides throwing all of my Go code into a subfolder and only running go mod init in that subfolder, is there a way to prevent go mod tidy from referencing those buried files?



Solution 1:[1]

https://github.com/golang/go/wiki/Modules#can-an-additional-gomod-exclude-unnecessary-content-do-modules-have-the-equivalent-of-a-gitignore-file

An empty go.mod in a directory will cause that directory and all of its subdirectories to be excluded from the top-level Go module.

In the infrastructure directory, touch go.mod creates an empty file and if I go mod tidy in the root folder, the go.mod file only contains the modules my project actually uses.

Solution 2:[2]

go mod init looks for configuration files and, if found, installs the modules.

Avoid this "helpful" behaviour by running go mod init [Edit] before cdk init app in a subdirectory:

# ...
npx cdk init app --language typescript
cd ..
mkdir src
cd src
go mod init example
go mod tidy
cd ..

This creates an empty go.mod, as expected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Reddy
Solution 2