LoginSignup
0

More than 1 year has passed since last update.

VSCodeで複数のgo.modを持つディレクトリを開くとBrokenImportが出る

Last updated at Posted at 2022-11-30

問題

VSCodeで開いるプロジェクトディレクトリ下に複数のgo.modが存在すると、BrokenImportのメッセージが出てしまいます。

Screen Shot 2022-11-30 at 19.27.21.png

解決法

go.modが存在するディレクトリがそれぞれworkspaceであることを明示するために go.work を作成します。

例えば./gin/go.mod ./http/go.mod があるとしたら以下を実行します。

$ go work init ./gin ./http

そうすると以下のファイルがプロジェクトディレクトリ直下に作成されます

go.work
go 1.18

use (
	./gin
	./http
)

go.modが多い場合は、go work initを実行してできた空のgo.workにエディタのサジェストに頼りながら手入力するのも速いかもしれません。
Screen Shot 2022-11-30 at 19.34.31.png

参考

(検索用)warningの中身

could not import github.com/gin-gonic/gin (cannot find package "github.com/gin-gonic/gin" in any of 
	/usr/local/go/src/github.com/gin-gonic/gin (from $GOROOT)
	/Users/xxxx/go/src/github.com/gin-gonic/gin (from $GOPATH))compilerBrokenImport

以前は以下のメッセージが出ており、vscode側の設定experimentalWorkspaceModuleでも解決できましたが、この設定は今年5月にdeprecatedとなったみたいです。https://github.com/golang/go/issues/52897

gopls requires a module at the root of your workspace.
You can work with multiple modules by opening each one as a workspace folder.
Improvements to this workflow will be coming soon, and you can learn more here:
https://github.com/golang/tools/blob/master/gopls/doc/workspace.md.

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0