Luigi.js配置文件使用import语句报错问题咨询
解决Luigi.js配置文件中
import语句报错问题 错误信息
Cannot use import statement outside a module
问题代码
import OpenIdConnect from '@luigi-project/plugin-auth-oidc'; const myData = () => { Luigi.setConfig({ auth: { use: 'openIdConnect', openIdConnect: { idpProvider: OpenIdConnect, authority: 'https://localhost:3000.com', client_id: 'client', scope: 'audience:server:client_id:client openID profile email groups', redirect_uri: '', automaticSilentRenew: true, accessTokenExpiringNotificationTime: 60, }, disableAutoLogin: false, }, // 其他配置内容... }); };
报错原因
该错误是因为当前JavaScript文件未被识别为ES模块,浏览器或Node.js默认将.js文件当作CommonJS模块处理,无法识别ES模块的import语法。
解决方案
方案1:标记文件为ES模块
在HTML中引用配置文件时,添加type="module"属性:
<script type="module" src="你的配置文件路径.js"></script>
注意:使用type="module"后,文件会遵循ES模块规则,且浏览器会启用跨域检查,本地开发需通过HTTP服务器访问,不能直接打开本地文件。
方案2:改用CommonJS语法
如果环境更适配CommonJS,将import替换为require:
const OpenIdConnect = require('@luigi-project/plugin-auth-oidc'); const myData = () => { Luigi.setConfig({ auth: { use: 'openIdConnect', openIdConnect: { idpProvider: OpenIdConnect, authority: 'https://localhost:3000.com', client_id: 'client', scope: 'audience:server:client_id:client openID profile email groups', redirect_uri: '', automaticSilentRenew: true, accessTokenExpiringNotificationTime: 60, }, disableAutoLogin: false, }, // 其他配置内容... }); };
方案3:通过项目配置启用ES模块
若使用Luigi CLI或构建工具(如Webpack),在项目根目录的package.json中添加以下配置,将所有.js文件标记为ES模块:
{ "type": "module" }
配置完成后,即可正常使用import语法。
内容的提问来源于stack exchange,提问作者Metgher Andrei
相关产品推荐
相关产品推荐

