Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share code in F# Azure Functions project

I'm currently developing F# Azure functions uinsg VS Code and I've laid out my project as such:

ProjectFolder
    -> Function1
        -> function.json
        -> run.fsx
    -> Function2
        -> function.json
        -> run.fsx

Given that F# doesn't support folders what's the best way to share code (especially types) between the two functions?

like image 242
Slugart Avatar asked Jul 12 '17 19:07

Slugart


1 Answers

F# compiler supports folders just fine. You may be referring to the fact that Visual Studio, in default configuration, does not allow one to add folders to F# projects - that is a true fact. But if you do somehow manage to add folders to your project file (either by manually editing the file, or with F# Power Tools), then the F# compiler won't have any problems with them.

But this is all irrelevant to your case anyway, because scripts (fsx) are not the same thing as compiled modules (fs). Scripts do not have a project to bind them together, and instead must #load each other in order to use each other's code. And #load can be done from any path whatsoever.

For example, you might want to lay out your code like this:

ProjectFolder
    -> Common
        -> Helpers.fsx
    -> Function1
        -> function.json
        -> run.fsx
    -> Function2
        -> function.json
        -> run.fsx

And then, within Function1/run.fsx, load the file Helpers.fsx using relative path:

// Function1/run.fsx
#load "../Common/Helpers.fsx"

let x = Helpers.someFunction()

As is evident from the example above, a script loaded this way will appear within the host script as a module named after the script file.

This works, but over time it will become very messy. I highly recommend going with precompiled code instead. This way, you can put common code in a shared library and reference it from both functions.

I very much recommend this recent video from NDC Oslo. It talks very well about these things and more.

like image 147
Fyodor Soikin Avatar answered Nov 09 '22 00:11

Fyodor Soikin