已经简单说过mjml_nif使用了rustler+rustler-precompiled 进行nif 的构建,同时官方也写了一篇相关的博客进行介绍
使用说明
- 配置依赖
def deps do
[
{:rustler_precompiled, "~> 0.7"}
]
end
- 配置native 使用
可以是一个独立的模块,命名上可以添加Native 比较符合习惯
defmodule RustlerPrecompilationExample.Native do
version = Mix.Project.config()[:version]
use RustlerPrecompiled,
otp_app: :rustler_precompilation_example,
crate: "example",
base_url:
"https://github.com/philss/rustler_precompilation_example/releases/download/v#{version}",
force_build: System.get_env("RUSTLER_PRECOMPILATION_EXAMPLE_BUILD") in ["1", "true"],
targets:
Enum.uniq(["aarch64-unknown-linux-musl" | RustlerPrecompiled.Config.default_targets()]),
version: version
# When your NIF is loaded, it will override this function.
def add(_a, _b), do: :erlang.nif_error(:nif_not_loaded)
end
version = Mix.Project.config()[:version]
- 官方示例的一个效果
可以看到预编译的包放在github 的release 中,下载已经使用都很方便
mjml-nif 的使用
- 效果
与rustler-precompiled 官方示例效果是一样的
- Native 配置
defmodule Mjml.Native do
mix_config = Mix.Project.config()
version = mix_config[:version]
github_url = mix_config[:package][:links]["GitHub"]
targets = ~w(
aarch64-apple-darwin
aarch64-unknown-linux-gnu
aarch64-unknown-linux-musl
riscv64gc-unknown-linux-gnu
x86_64-apple-darwin
x86_64-pc-windows-gnu
x86_64-pc-windows-msvc
x86_64-unknown-linux-gnu
x86_64-unknown-linux-musl
)
nif_versions = ~w(
2.15
2.16
)
use RustlerPrecompiled,
otp_app: :mjml,
crate: "mjml_nif",
base_url: "#{github_url}/releases/download/v#{version}",
force_build: System.get_env("MJML_BUILD") in ["1", "true"],
version: version,
targets: targets,
nif_versions: nif_versions
def to_html(_mjml, _render_options), do: error()
defp error(), do: :erlang.nif_error(:nif_not_loaded)
end
mix_config = Mix.Project.config()
说明
开源项目使用,推荐与github action 集成起来,如果是自己的项目可以使用docker进行构建(可以方便生成好不同系统的nif 包)
参考资料
https://dashbit.co/blog/rustler-precompiled
https://hexdocs.pm/rustler_precompiled/RustlerPrecompiled.html
https://github.com/philss/rustler_precompiled
https://github.com/rusterlium/rustler
https://docs.rs/crate/rustler/latest
https://github.com/adoptoposs/mjml_nif
https://github.com/philss/rustler_precompilation_example
https://github.com/adoptoposs/mjml_nif/blob/main/.github/workflows/release.yml