jint 关于模块加载的一些说明
jint 默认是基于es6 进行的模块加载,但是也是支持类似node commonjs 的require 加载, 但是注意require 模式更多是一个from 的别名,只能在一些场景使用,实际还是推荐基于es6 模块方式
使用说明
- 默认有base check (_restrictToBasePath 默认为true)
实际是一个安全处理,否则会造成文件遍历问题
- require 实际是import 的一个别名 如下代码可以看出来
if (Modules.RegisterRequire)
{
// Node js like loading of modules
engine.Realm.GlobalObject.SetProperty("require", new PropertyDescriptor(new ClrFunction(
engine,
"require",
(thisObj, arguments) =>
{
var specifier = TypeConverter.ToString(arguments.At(0));
return engine.Modules.Import(specifier);
}),
PropertyFlag.AllForbidden));
}
- es6 写法与require 可以混合使用
一种是配置开启RegisterRequireoptions.Modules.RegisterRequire = true;
一种是通过注册module 的时候进行一个global 替换,比如
_engine.Modules.Add("@scope/platform-common", builder =>
{
builder.ExportObject("platform", platform);
builder.AddSource("globalThis.require = importNamespace;");
});
- 对于三方包的加载 具体可以通过type 添加,或者通过
options.AllowClr
但是注意使用,需要明确引用(importNamespace),当然require 别名也是一种方法,这样更加符合node 模块的开发, 在代码方法引用模块,require 与一般es 6 模块开头的import from 效果实际与from 有点类似(因为require 就是一个别名,但是注意需要开启options.Modules.RegisterRequire = true
)
说明
jint 基本上是实现了es6 模块的加载机制,基本够用,jint 实现了一个自己的模块加载实现,默认是DefaultModuleLoader,当然也可以实现自己的,可以在Engine 创建的时候指定自己的实现options.Modules.ModuleLoader)
比如基于s3实现管理,或者基于zip包,或者是dotnet 的resource 机制,这样有利于模块分发