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

如何将CommonJS的require转换为ES6+ import?解决Node.js模块导入时的TypeError问题

Fixing ES6 Import Error for Your Node.js Server App

Hey there! Let's work through this issue where converting your CommonJS require to ES6 imports is throwing a TypeError: (0 , _app.default) is not a function error.

First, let's break down what your original code is doing:

const serverApp = require('../dist/server/app.js').default;

This line imports the entire CommonJS module and explicitly grabs its default property — which means your Webpack/Babel build is outputting a module where the actual app function lives under the default key of the exported object.

Correct ES6 Equivalents

Here are the ES6+ syntax options that match the exact behavior of your original code:

1. Explicitly Import the Default (Most Clean)

If your build correctly maps ES6 default exports to the default property in CommonJS, this should work:

import serverApp from '../dist/server/app.js';

This syntax is designed to directly reference the default export of the module, aligning perfectly with your original .default access.

2. Alias the Default Export (Explicit, Same Behavior)

If the first option throws an error, you can explicitly alias the default export to mirror your original code's logic:

import { default as serverApp } from '../dist/server/app.js';

This is a more verbose but explicit way to grab the default property and name it serverApp.

3. Import the Entire Module Object (Fallback)

If neither of the above works, this approach perfectly replicates the behavior of your original require statement:

import * as appModule from '../dist/server/app.js';
const serverApp = appModule.default;

By importing the entire module as an object (appModule), you access its default property exactly like you did with require().default. This is the most reliable fallback if your build's module handling has edge cases.

Why the Error Happens

The TypeError means the default property of your imported module is either undefined or not a function. Here are common fixes:

  • Check Your Source Export: Ensure the original code (before build) uses export default serverApp instead of module.exports = serverApp. If you're using CommonJS in the source, Babel/Webpack might map module.exports to the default export differently.
  • Adjust Babel Configuration: In your @babel/preset-env settings, set the modules option to commonjs (or leave it as auto) so Babel correctly converts ES6 exports to CommonJS-compatible objects with a default property.
  • Verify Webpack Target: Since this is a Node.js server, set target: 'node' in your Webpack config. This ensures Webpack doesn't bundle browser-specific module handling that could break Node's module resolution.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:28:11