In my case adding export {};
was not enough.
I met this error in the webpack.config.ts
file. The error message looked like this:
'webpack.config.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module.ts(1208)
When I added export {};
I got another error:
SyntaxError: Unexpected token ‘export'
at Object.compileFunction (node:vm:352:18)…
I tried to change tsconfig.json
module option from:
{
"compilerOptions": {
"module": "EsNext",
"isolatedModules": true
},
to:
{
"compilerOptions": {
"module": "CommonJS",
"isolatedModules": true
},
,because webpack.config.ts had commonjs syntax like module.export ={}
. Unfortunately, it didn't work too. I discovered that there were no type definitions added to the project, so I run:
npm install --save-dev ts-node @types/node @types/webpack
and everything was fine. The file was recognized as a module thanks to export {};
.
Of course, using export {};
to make the file a module is just a workaround, not a solution. I could
- change webpack.config file extension to .js instead of .ts and stay with the commonJS module format
- change to import/export statements in ES modules format and use the .mjs file extension, because Node.js has stable support for ES modules since version 13.2.0 was introduced. Nevertheless, that would trigger other problems with changing commonJS syntax
Can I use as es-modules for webpack config?
- leave .ts file extension, follow the webpack configuration guide for typescript and use ES modules
link
I chose the third option and had to add import 'webpack-dev-server';
to avoid type errors. My configuration changed from this:
export {};
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = (env) => {...}
to this:
import * as path from 'path';
import * as webpack from 'webpack';
import 'webpack-dev-server';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const config = (env: { [x: string]: any; }): webpack.Configuration => {...}
export default config;