For library, how to determine user code whether has imported expected packages
# user code
import std/re
# lib code
when import("std/re"):
echo "std/re was imported"
It's not clear what you mean, but there should never be a case where you need to check in library code the import of the user code.
If your library has required dependencies, then your module should re-export them.
For example :
# Package foo
# src/foo/bar.nim
proc bar*() = discard
# src/foo.nim
import bar
proc foo*() = discard
export bar # bar() is a
# external user code
import foo
foo()
bar()
Otherwise you can use when compiles(...): doStuff() to check at compile time if the module is present :
# import std/re
when compiles(re):
echo "OK import re"
else:
echo "KO import re"
import strutils
when compiles(strutils):
echo "OK import strutils"
else:
echo "KO import strutils"
But I really don't know why you would need this construct and this feels like a XY problem.
There is no unified solution for this. Typically what I do in such scenarios is I add a compile-time switch as that is typically how I design the lib at that point. So if the user wants X they need to compile with nim c -d:enableStdRe <yourfile>.
In your code you can then put the code inside of a when defined block:
when defined (enableStdRe):
import std/re
<rest your code>
That way, if the flag is passed, this code is made available. If the flag is not provided, that code will be "cut out" and thus not exist.
That would be the most efficient "compile-time" way to do this anyway.