Why would Webpack 4 give loader errors for CJS and UMD packages?

224 Views Asked by At

I have a few packages that were compiling via tsc alone. This was causing issues when those packages were imported into an app that uses Webpack 4. I decided to try out using vite in my package and just exporting cjs format. I figured since it's bundling everything, it should "just work". I had had issues when using Webpack 5, because there are various conflicts when a host app uses 4 and imports a package using 5 due to the way both versions modify global variables(https://github.com/webpack/webpack/issues/17730).

Now that I am exporting cjs I get:

I updated my relevant package.json from:

  "type": "module",
  "types": "dist/src/index.d.ts",
  "main": "dist/index.js",

to

  "types": "dist/src/index.d.ts",
  "main": "dist/index.js",
  "module": "dist/index.mjs",

I also updated the host app resolve config as shown in Force Webpack 4 to import cjs only and never esm with typescript.

I am now getting this error:

ERROR in ../cai-plugin/packages/common/dist/index.js 1:573
Module parse failed: Unexpected token (1:573)
You may need an appropriate loader to handle this file type.

I thought Webpack 4 should handle cjs no issue? I tried the same with umd and the error was the same except index.umd.js had the incorrect syntax. That surprised me even more.

1

There are 1 best solutions below

0
On BEST ANSWER

This pretty much relates to Simple webpack build fails because of new ES syntax.

I updated my package's Vite config so the host app could consume things no issue in Webpack 4.

// vite.config.js
import { resolve } from 'path';
import { defineConfig } from 'vite';
import typescript from '@rollup/plugin-typescript';

export default defineConfig({
  build: {
    target: 'es2015',
    lib: {
      // Could also be a dictionary or array of multiple entry points
      entry: resolve(__dirname, 'src/index.ts'),
      formats: ['cjs', 'es'],
      // the proper extensions will be added
      fileName: 'index',
    },
    rollupOptions: {
      plugins: [typescript()],
    },
  },
});

My TS config target also was downgraded: "lib": ["ES2015", "dom"],