Search code examples
webpacknext.jsnode-modulestypeormreflect-metadata

What happens when `typeorm/browser/index.js` throws "Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' error"?


I recently came up with a new pure JS web app running on Node.js (not importing anything about TypeScript), having [email protected] as the framework and [email protected] as the ORM layer to an Azure SQL server.

Everything works fine and I've connected to the SQL server successfully.

However, I accidentally deleted package.json without committing it. Anyway, I managed to re-install the missing packages, typeorm, reflect-metadata and mssql. But after the re-installation, when I started the dev server, I encountered a new error I've never seen before.

error - ./node_modules/typeorm/browser/index.js
Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (3:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| /*!
|  */
> import "reflect-metadata";
| // -------------------------------------------------------------------------
| // Commonly Used exports

I've searched a bit and found it might be something related to webpack. But I have not much clue on this. The below is my next.config.js btw.

module.exports = {
  reactStrictMode: true,
  webpack: (config, options) => {
    config.module.rules.push({
      test: /\.html$/i,
      loader: "html-loader",
    });

    return config;
  },
};

I've tried some basic sanity checks like deleting the node_modules/ and reinstalling but no luck. Does anyone have a clue on what's happening and how to fix it?


Update:

With the help of @hej and this issue on GitHub, I added this part to my next.config.js and it works!

    config.module.rules.push({
      test: /\.[jt]sx?$/,
      include: [/node_modules(.*[/\\])+typeorm/],
      type: "javascript/auto",
      use: "babel-loader",
    });

Solution

  • Try add this to your webpack config:

    {
      module: {
        rules: [
          {
            test: /\.[jt]sx?$/,
            include: [/node_modules(.*[/\\])+typeorm/],
            use: "babel-loader",
          },
        ],
      },
    }