You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Node.js中用ES7语法导入passport-google-oauth20模块对象的方法

问题:ES模块语法下如何正确导入passport-google-oauth20的GoogleStrategy?

原本使用CommonJS语法导入GoogleStrategy:

var GoogleStrategy = require('passport-google-oauth20').Strategy;

由于package.json中设置了"type": "module",无法再使用require()这类CommonJS语法,尝试用ES模块语法改写时:

import GoogleStrategy from ('passport-google-oauth20').Strategy

无法正常运行,求正确的ES模块导入写法。

附package.json相关内容:

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "nodemon index.js"
  },
}

解决方案
  • 命名导入并重命名(推荐写法):
    passport-google-oauth20的Strategy属于命名导出而非默认导出,因此需要用花括号指定导出项,再通过as重命名为GoogleStrategy:

    import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
    
  • 导入整个模块后提取属性:
    先导入完整模块对象,再从中取出Strategy属性赋值给GoogleStrategy:

    import passportGoogle from 'passport-google-oauth20';
    const GoogleStrategy = passportGoogle.Strategy;
    

以上两种写法均可在"type": "module"环境下正常运行,第一种更贴合ES模块的编码习惯,代码更简洁。


内容的提问来源于stack exchange,提问作者user20345646

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 22:50:22