简体   繁体   English

"如何为使用 bazel 构建的 Go 项目设置 vscode?"

[英]How can I setup vscode for Go project built with bazel?

gVisor recently added a gopath BUILD rule that creates a canonical GOPATH tree from the source. gVisor最近添加了一个gopath BUILD规则 ,它从源代码创建一个规范的GOPATH树。

You may be able to use that the edit more effectively from VScode. 您可以从VScode更有效地使用该编辑。

The linked gVisor rule now proxies a more canonical implementation链接的 gVisor 规则现在代理更规范的实现

This setup worked for me:此设置对我有用:

  1. In your workspace's root BUILD file you can add the following build rule在工作区的根 BUILD 文件中,您可以添加以下构建规则
# in BUILD.bazel
load("@io_bazel_rules_go//go:def.bzl", "go_path")

go_path(
    name = "gopath",
    mode = "link",
    deps = [
        "//my/binary/here",
        "//any/other/binaries/you/want/linked",
    ],
)

(if you don't yet have a gazelle import for the bazelbuild/go_rules, you would need to import it for bazel) (如果您还没有为 bazelbuild/go_rules 导入瞪羚,则需要为 bazel 导入它)

# in WORKSPACE
http_archive(
    name = "io_bazel_rules_go",
    sha256 = "8e968b5fcea1d2d64071872b12737bbb5514524ee5f0a4f54f5920266c261acb",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.28.0/rules_go-v0.28.0.zip",
        "https://github.com/bazelbuild/rules_go/releases/download/v0.28.0/rules_go-v0.28.0.zip",
    ],
)
  1. Build this command to create a symlinked folder in your blaze-out at bazel-bin/gopath that contains links to each of your dependencies.构建此命令以在bazel-bin/gopath的 blaze-out 中创建一个符号链接文件夹,其中包含指向每个依赖项的链接。 You'll have to do this any time you add a new dependency.每次添加新依赖项时都必须这样做。 You will see a line for each symlink created.您将看到创建的每个符号链接都有一行。
bazel build :gopath
  1. (assuming you're using VSCode with the Golang extension ) Set your workspace settings for the go extension to point to this gopath. (假设您使用带有Golang 扩展的 VSCode )将 go 扩展的工作区设置设置为指向此 gopath。 Note you'll need to have it be a worspace trusted extension in order for this to work.请注意,您需要将其设为工作空间受信任的扩展程序才能使其正常工作。
// In .vscode/settings.json
{
    "go.gopath": "/YOUR ABSOLUTE PATH TO YOUR WORKSPACE//bazel-bin/gopath"
}
  1. Restart VSCode重启 VSCode

  2. Enjoy!享受!

NOTE: if you have a go.mod file in your root dir, this will not work.注意:如果你的根目录中有一个 go.mod 文件,这将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM