babel/babel

[Bug]: export default is not a function

jhgeluk opened this issue · 7 comments

💻

  • Would you like to work on a fix?

How are you using Babel?

babel-loader (webpack)

Input code

import center from '@turf/center';
let boundingBoxPolygon = [];
center(boundingBoxPolygon);

Configuration file name

No response

Configuration

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
	target: 'node',
	externals: [nodeExternals()],
	devtool: 'source-map',
	entry: {
		'server': './src/server/index.js',
		'server.prod': './server.prod.js',
	},
	output: {
		path: path.resolve(process.cwd(), 'dist', 'server'), // Output directory
		filename: '[name].js',
		libraryTarget: 'commonjs2',
	},
	optimization: {
		moduleIds: 'named',
		minimize: false,
	},
	module: {
		rules: [
			{
				test: /\.(mjs|js)$/,
				use: {
					loader: 'babel-loader',
					options: {
						presets: [['@babel/preset-env'], ['@babel/preset-react']],
						plugins: [['@babel/transform-runtime']],
					},
				},
				exclude: /node_modules/,
			},
		],
	},
	resolve: {
		extensions: ['.mjs', '.js', '...'],
	},
};

Current and expected behavior

I have a legacy project written in CommonJS, so I had to bundle and transpile this project in combination with Babel. Almost everything works fine, except a few import statements from the package '@Turf'.

My project consists of .js (CommonJS) files and .mjs files (ECMAscript 6). This interoperability works good for the most part, but when I import import center from '@turf/center'; in one of my .mjs files, I get this error:
center_ is not a function

When I look at the bundled code I see this:

// EXTERNAL MODULE: external "@turf/center"
var center_ = __webpack_require__("@turf/center");

But when I console.log the center_ variable, I see that it exports a default function:
{ default: [Function: center] }

And in the code it's trying to access this function like so:
center_(boundingBoxPolygon);

Which does not work, and raises the "center_ is not a function" error. I expect babel to automatically get the ".default" function, instead of trying to invoke the object.

Environment

Babel versions:

  • @babel/core: 7.24.5
  • babel-loader: 9.1.3

Webpack versions:

  • webpack: 5.91.0

Possible solution

No response

Additional context

I'm working on a legacy project that's using CommonJS, we need to use some new libraries that are only compatible with ES6. So we incorporated some .mjs files in the project.

This works fine in our development server/environment, where we use:

require('@babel/register')({
	presets: ['@babel/preset-env'],
});

But when we try to bundle and transpile the code we get this issue.

Hey @jhgeluk! We really appreciate you taking the time to report an issue. The collaborators on this project attempt to help as many people as possible, but we're a limited number of volunteers, so it's possible this won't be addressed swiftly.

If you need any help, or just have general Babel or JavaScript questions, we have a vibrant Slack community that typically always has someone willing to help. You can sign-up here for an invite.

When using Webpack, import&export are left untouched by Babel because webpack transforms them. I suggest asking in the Webpack repository if they have an option similar to https://babeljs.io/docs/babel-plugin-transform-modules-commonjs#importinterop. Maybe you can find some info in webpack/webpack#7973.

You can explicitly add @babel/plugin-transform-modules-commonjs to the Babel config to force Babel to transpile ESM to CJS also when using webpack, but I recommend trying an alternative solution because webpack won't be able to tree-shake your imports anymore if they are first transpiled by Babel.

Thanks for your quick reply. I've tried @babel/plugin-transform-modules-commonjs but that causes a whole new set of problems, since it will look for files that are not in the dist folder.

Hi @nicolo-ribaudo ,

I was wondering if you could please help me. I've given up on the idea of bundling the code with webpack, since it will take too much time for it to be resolved.

So I'm just transpiling it with babel, like so: npx babel src/server --out-dir dist/server --keep-file-extension.

But when I do a request to my server, I get this response:

Error: require() of ES Module /src/services/pdf/index.mjs not supported.\nInstead change the require of /src/services/pdf/index.mjs to a dynamic import() which is available in all CommonJS modules.

I don't understand why this does not work, since I'm using dynamic imports and not require statements.

All my code worked when I was using:

require('@babel/register')({
	presets: ['@babel/preset-env'],
});

But it's not advised to use that in a production environment.

Can you try adding exclude: ["transform-dynamic-import"] to the babel/preset-env options, so that it does not transform dynamic imports to require()?

Thanks again for the quick response.

Now I get this error:
require is not defined in ES module scope, you can use import instead