How do I resolve “cannot find module for path X” importing a local Go module?

后端 未结 1 2076
面向向阳花
面向向阳花 2020-12-01 11:10

In my Go project, I want to break out some generic functionality into a Go module, separate from the main project. I\'m doing this outside of GOPATH in keeping with go\'s fu

相关标签:
1条回答
  • 2020-12-01 12:04

    So you wrote a Go "library" module which:

    • you don't want to publish on GitHub or elsewhere
    • you want to import and use it in your project (the "main" module).

    Use the replace directive to solve this problem.

    Given the module name "X" as you've called it, in your main module add the following lines:

    require "X" v0.0.0
    replace "X" v0.0.0 => "{local path to the X module}"
    

    The path should point to the root directory of the module, and can be absolute or relative.

    To import package util from module X:

    import "X/util"
    

    (You don't import modules. You import packages from modules.)


    Explanation

    Go's module functionality is designed for publicly published modules. Normally, a module's name is both its unique identifier and the path to its public repo. When your go.mod declares a module dependency with the require directive, Go will automatically find and retrieve the specified version of the module at that path.

    (See also in the Go Modules FAQ, Can I work entirely outside of VCS on my local filesystem?)

    If, for example, your go.mod file contains require github.com/some/dependency v1.2.3, Go will retrieve the module from GitHub at that path. But if it contains require X v0.0.0, "X" isn't an actual path and you will get the error cannot find module for path X.

    The replace directive allows you to specify a replacement path for a given module identifier and version. There are many reasons you'd want to do this, such as to test changes to a module before pushing them to the public repo. But you can also use it to bind a module identifier to local code you don't ever intend to publish.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题