Node.js中使用await处理模块导出/引入报错,求解决方案
问题解决:顶层await报错的根本原因与修复方案
你遇到的核心问题是顶层await仅支持ES模块(ESM),而你的代码是CommonJS模块——Node.js默认将.js文件视为CommonJS,在CommonJS里无论怎么放置await都会触发那个语法错误。
下面提供两种可行的修复方案:
方案一:切换到ES模块(推荐)
Node.js从v14.8开始支持顶层await,但必须在ESM环境下运行。切换方法有两种:
方法1:通过package.json启用ESM
在项目根目录的package.json中添加"type": "module"配置:
{ "type": "module" }
然后修改你的config.js,将CommonJS语法替换为ESM语法:
import wjConfig from 'wj-config'; import fs from 'fs'; const loadJsonFile = (fileName, isRequired) => { const fileExists = fs.existsSync(fileName); if (fileExists) { const data = fs.readFileSync(fileName); return JSON.parse(data); } else if (isRequired) { throw new Error(`Configuration file ${fileName} is required but was not found.`); } return {}; }; const env = new wjConfig.Environment(process.env.NODE_ENV); const config = wjConfig() .addObject(loadJsonFile('./config/config.json', true)) .name('Main Configuration') .addObject(loadJsonFile(`./config/config.${env.value}.json`)) .name('Env Configuration') .addEnvironment(process.env) .includeEnvironment(env) .createUrlFunctions() .includeValueTrace() .build(); // 现在顶层await可正常使用 export default await config;
主入口index.js也要同步改用ESM的import语法:
import config from './config.js'; // 直接使用配置 console.log(config);
方法2:修改文件后缀为.mjs
将config.js改名为config.mjs,index.js改名为index.mjs,同样用import/export替换require/module.exports,无需修改package.json即可启用ESM环境。
方案二:在CommonJS中导出Promise(无需切换模块)
如果不想切换到ESM,可以直接导出一个Promise,然后在主入口的异步函数中等待它完成:
修改config.js:
const wjConfig = require('wj-config'); const fs = require('fs'); const loadJsonFile = (fileName, isRequired) => { const fileExists = fs.existsSync(fileName); if (fileExists) { const data = fs.readFileSync(fileName); return JSON.parse(data); } else if (isRequired) { throw new Error(`Configuration file ${fileName} is required but was not found.`); } return {}; }; const env = new wjConfig.Environment(process.env.NODE_ENV); // 直接导出build返回的Promise const configPromise = wjConfig() .addObject(loadJsonFile('./config/config.json', true)) .name('Main Configuration') .addObject(loadJsonFile(`./config/config.${env.value}.json`)) .name('Env Configuration') .addEnvironment(process.env) .includeEnvironment(env) .createUrlFunctions() .includeValueTrace() .build(); module.exports = configPromise;
主入口index.js中用async函数包裹逻辑:
const configPromise = require('./config.js'); async function runApp() { const config = await configPromise; // 在这里使用配置 console.log(config); } // 启动应用 runApp();
额外说明
如果wj-config的build()方法是同步的(返回普通对象而非Promise),那await其实是多余的——但即使保留,在ESM环境下也不会报错,只是直接返回原对象而已。
内容的提问来源于stack exchange,提问作者José Ramírez
相关产品推荐
相关产品推荐

