Navigating CommonJS and ES Module Challenges in Express.js
Introduction
When we import other JavaScript packages into a Node.js project, we may need some help. For instance, if we import an ES Module package but our project is using CommonJS, we may not be successful because CommonJS does not allow the importation of the ES Module packages. However, we can solve this problem by changing our project type to a pure ES Module package, which allows ES Module to access both ES Module and CommonJS packages.
However, the real world is not that simple. Let’s take a look at a more complex problem.
What’s the Real Problem?
Imagine that you are importing a legacy library that your company maintains. The library is written in Typescript and is exported as an ES Module package, but it was not built as a pure ESM package. This means that it is neither an ES Module nor a CommonJS package. If this were the only issue, you could fix the legacy library by changing it to an ESM package.
However, if this library imported other packages that are neither ES Module nor CommonJS libraries, and then exported them as an ES Module package, you would encounter an awkward error message when you compiled your project. The error message would ask you to add the following to your package.json
{
"type": "module"
}After you change your package.json, you may encounter another error message when you compile your project that asks you to remove it.
This will be an endless fix for the ES Module package.
Before we solved the problem, let’s figure out what is going on.
Explaining the problem
The problem is that our project considers the imported package an ES Module, but some of the code is written in CommonJS. The compiler cannot identify the code and the error occurs.
Environment
Node.js: v19.8.1
npm: 9.6.4
Express.js: 4.18.2
Wepack: 5.75.0
How can we handle this problem?
You can solve this problem through Webpack. There is an example with the Express.js server.
The following shows the Express.js project structure.
├── docker-compose.yaml
├── Dockerfile
├── package.json
├── README.md
├── src
│ ├── app.ts
│ ├── controllers
│ ├── modules
│ └── routes
├── test
│ ├── myTestScript.test.ts
├── tsconfig.json
├── vite.config.ts
├── webpack.config.cjs
└── yarn.lockThe webpack.config.cjs should look like
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin')
const config = {
target: 'node',
entry: rootDir('src/app.ts'),
node: {
__dirname: false,
__filename: true,
global: true
},
output: {
path: rootDir('dist'),
filename: '[name].bundle.cjs'
},
module: {
rules: [{
test: /\.[tj]s$/,
use: 'ts-loader',
exclude: /node_modules/,
}]
},
resolve: {
extensions: ['.js', '.ts'],
conditionNames: ['import', 'require', 'node'],
},
snapshot: {
// Note: skip yarn link protocol path to avoid warning, Ref: https://github.com/webpack/webpack/pull/14509#issuecomment-1237348087
managedPaths: [/(node_modules\/(?!@\/|SVG)).*/],
},
stats: {
errorDetails: true,
colors: true,
},
ignoreWarnings: [
// some warning that you wanted to ignore
{
module: file,
message: /some regular expression/
}
],
plugins: [
new CopyPlugin(
{
patterns: [
// Copy static asset files so that they can be served from output directory as swagger-ui-dist does not work
// with webpack.
rootDir('Your Static files'),
]
}
),
],
}
function rootDir(dir) {
return path.join(__dirname, '..', dir);
}
module.exports = config;Conclusion
The article briefly introduces the benefit of ES modules in importing CommonJS and gives an example in a real-world scenario.
Get Cheyu Wu’s stories in your inbox
Join Medium for free to get updates from this writer.
The article explains the problems in a real-world scenario and gives a solution to the problem with Webpack 5.
If there are any problems, feel free to ask or leave a comment.
Hope you guys don’t spend whole day looking for this problem like I did.








