使用 Layer 时,ES Module 的 import 路径的问题 #203
c0per
started this conversation in
Serverless
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
在部署Next.js应用时,编译后的js代码中存在导入ES Module的情况(
import ...
)。同时,我将node_modules放在了一个Layer中。在运行时,发现Layer被正确挂载在
/opt
目录下,所有的commonjs module
的导入(require()
)都是正常的,但import
会出现如下报错:原因是Node.js在导入ES Module时不会参考
NODE_PATH
环境变量,而是从当前目录开始,逐步向上寻找node_modules
。通过在scf_bootstrap
中输出module.paths
和process.env.NODE_PATH
(应该是ES Module的导入PATH),会得到这样的结果:ES Module的导入PATH中没有/opt(Layer的内容),所以导致了上述
[ERR_MODULE_NOT_FOUND]
的问题。即使试图在scf_bootstarp
中进行module.paths.push('/opt'); module.paths.push('/opt/node_modules');
,也无法解决问题。(貌似Node.js不支持动态修改module.paths
)目前我使用的解决方案是配置Babel,编译输出不含ES Module的代码。
.babel.rc
:这样可以解决运行时报错的问题,但只能输出不含
ES Module
的代码了。网上没有查询到修改ES Module import path的方法,不知道这种问题有没有更好的解决方案。
Beta Was this translation helpful? Give feedback.
All reactions