exposing (..)
允许你直接调用包中所有的函数。
例如,如果SamplePackage有函数x和y,import SamplePackage
将允许你调用 SamplePackage.x
和 SamplePackage.y
,而 import SamplePackage exposing (..)
则允许你直接调用 x
和 y
,无需指定它们所在的包。
请注意,import SamplePackage exposing (x)
允许你直接调用 x
,但你仍然需要使用 SamplePackage.y
调用 y
。同样地,import SamplePackage exposing (x, y)
将允许你调用 x
和 y
,但不允许你调用包中的其他函数。
import Graphics.Element exposing (Element, show)
对于这个例子,它仍然可以正常工作。
exposing (..)
和 exposing (Element, show)
之间的区别。 - wiserimport Graphics.Elements
,你仍然可以通过以下方式访问 Graphics.Element
模块中的所有公共内容:Graphics.Element.Element
和 Graphics.Element.show
。 - wiser这是一个旧问题,但我仍然会通过另一种思路来解释exposing (..)
,并解释一下为什么通常不是一个好主意。如果你有Python编程背景,那么你可以将其视为Python中的from module import *
。这是Elm代码:
import Graphics.Element exposing (Element, show)
在Python中,它看起来会像这样:
from Graphics.Element import Element, show
而这段 Elm 代码:
import Graphics.Element exposing (..)
在Python中,它会像这样:
from Graphics.Element import *
{- someOtherModule.elm -}
import Graphics.Element exposing (..)
{- ... more code ... -}
someImage = rotatedImage (pi / 2) sourceImage -- Angle is in radians
myGraphics
模块中调用不同的函数,因此你需要导入它:{- someOtherModule.elm -}
import Graphics.Element exposing (..)
import myGraphics exposing (..)
{- ... more code ... -}
someImage = rotatedImage (pi / 2) sourceImage -- WHOOPS, angle is now in degrees!
突然间,someImage
的旋转角度发生了改变!当你导入了 myGraphics
时,你是否想要改变页面上 someImage
的外观呢?几乎肯定不是。
这就是为什么一旦你的代码相对稳定,就应该避免使用 import Foo exposing (..)
。它在开发过程中非常有用,因为你不必不断地回到代码顶部来添加另一个名称到你的 import
语句中。但是一旦你完成了模块的大量开发,并且只偶尔对其进行更改,你应该真正开始使用 import Foo exposing (just, the, names, you, need)
。这样你就能避免许多陷阱。