如何将CommonJS的require转换为ES6+ import?解决Node.js模块导入时的TypeError问题
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 serverAppinstead ofmodule.exports = serverApp. If you're using CommonJS in the source, Babel/Webpack might mapmodule.exportsto the default export differently. - Adjust Babel Configuration: In your
@babel/preset-envsettings, set themodulesoption tocommonjs(or leave it asauto) so Babel correctly converts ES6 exports to CommonJS-compatible objects with adefaultproperty. - 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

