当前位置: > > > > 使用不同的 go.mod 文件构建 go 项目
来源:stackoverflow
2024-04-22 22:51:35
0浏览
收藏
哈喽!大家好,很高兴又见面了,我是的一名作者,今天由我给大家带来一篇《使用不同的 go.mod 文件构建 go 项目》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!
问题内容
我想知道如何使用不同的 go.mod 文件构建 go 项目。假设我想使用项目 B go.mod 文件在项目 B 模块内构建项目 A,而不复制文件。这意味着我想使用项目 B 中的依赖项来构建项目 A。
正确答案
手动选项
“模块文件”指的是 go.mod 和 go.sum
- 将项目 a 的模块文件重命名或移动到某些临时名称/位置
- 将项目 b 的模块文件复制到项目 a
- 编辑项目a中新复制的go.mod文件,并更改模块名称:
module github.com/x/b
更改为 module github.com/x/a
- 构建项目 a 中需要构建的任何内容
- 删除项目 a 中的活动模块文件
- 恢复您在步骤 1 中重命名或移动的项目 a 的正确模块文件
如果您需要经常执行这些步骤,可以使用 shell 脚本或批处理文件自动执行这些步骤。
使用构建命令
使用go help build
命令,我们可以看到构建标志-modfile
-modfile file in module aware mode, read (and possibly write) an alternate go.mod file instead of the one in the module root directory. a file named "go.mod" must still be present in order to determine the module root directory, but it is not accessed. when -modfile is specified, an alternate go.sum file is also used: its path is derived from the -modfile flag by trimming the ".mod" extension and appending ".sum".
使用它,我们可以直接使用一组替代模块文件来构建项目 a 中的内容。
首先,标志描述表明它可以写入 go.mod 文件,因此创建项目 b 模块文件的副本来执行此操作可能仍然是一个好主意。
其次,如果出现以下情况,使用项目 b 的模块文件将会出现问题: 1. 项目 a 和项目 b 在其模块文件中声明了不同的模块名称,并且 2. 项目 a 中的包导入了项目 a 中的其他包。模块名称决定了模块中包的导入路径,因此更改它可能会破坏导入。
所以最佳实践仍然应该是:
- 复制项目 b 的模块文件
- 更改副本中的模块名称
然后你可以运行这样的构建命令来构建项目a:
go build -modfile path/to/projectb/go.mod
首先,在某处创建一个文件夹 b
。然后在b
里面创建一个文件夹a
。然后使 b/b.go
:
package b const something = 1
然后制作b/a/a.go
:
package a import "b" func something() int { return b.Something }
然后返回b
文件夹,执行go mod init b
。完成。
今天关于《使用不同的 go.mod 文件构建 go 项目》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!