Can replace be used only locally?

Hi! I’m using replace in the go.mod file to compile local modules. This works fine locally even when different modules are involved, but it breaks the build when pushing to github (as obviously the …/ path doesn’t work there).

I cannot seem to find a way to tell the compiler to execute the replace only on condition, though. It’s not deadly, but it would save a lot of time to have multiple builds checked on the push event, instead of having to compile locally for different environments.

1 Like

Do you want to replace when you develop, but not replace when you push to github?
The thing to do is to remove the replace just after you have already pushed the replaced module, so everything compiles properly. Then commit without the replace.

I would also like not having to change the go.mod file back and forth.

I was thinkin that there could be a go.replace or go.local file that you would not commit and which would provide replace statements that override go.mod. But the go.sum file would need to be fixed too, so this wouldn’t work. If you commit the replaced module to github, remove the replace section from go.mod, and do go mod tidy, the go.sum file would change to reflect the new version of the replaced module. I don’t see a way out of this.

1 Like

Hello @Berto_ed_Sera,

You appear to be compiling local modules using the “replace” directive in your go.mod file. While this works perfectly locally, publishing to GitHub breaks the build since the ‘…/’ route does not function there.

Unfortunately, there is no method to execute the replace directive conditionally based on the environment. There are, however, a few potential solutions you might try:

  1. Create a vendor folder: Rather than using replace, you may vendor your local modules into your project. This guarantees that the compiler has access to the modules regardless of the environment.

  2. Use build tags: Build tags may be used to include or exclude specific files or packages based on the environment. You might, for example, use a build tag to include the replace directive just when compiling locally and not while building for production.

  3. Use a build script: Create a build script that builds your code for each environment and saves the generated binaries in distinct folders. This allows you to test many builds without manually compiling each one.

I hope these suggestions help.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.