JS-DevTools / ono

Wrap errors without losing the original message, stack trace, or properties
https://jstools.dev/ono/
MIT License
97 stars 11 forks source link

Weird CJS module hack is bombing Rollup builds #19

Open Prophet32j opened 1 year ago

Prophet32j commented 1 year ago

https://github.com/JS-DevTools/ono/blob/a1fa89a25e7432f7615af8b4179f842b5affccf2/src/index.ts#L10-L13

This code block is bombing my rollup build. Not caught during build. This code makes it into the bundle, and then it fails on runtime startup. module.exports.default is undefined and is killing the build.

/path-to-my-build/node_modules/@jsdevtools/ono/esm/index.js:12
 module.exports = Object.assign(module.exports.default, module.exports);
                                            ^
TypeError: Cannot convert undefined or null to object

I found this by preserving the modules from Rollup so I could get a good stacktrace to the code.

// my rollup
import commonjs from '@rollup/plugin-commonjs'
import nodeResolve from '@rollup/plugin-node-resolve'
import json from '@rollup/plugin-json'

export default {
  input: 'src/service.js',
  output: {
    // file: 'dist/service.js',
    dir: 'dist/',
    format: 'cjs',
    sourcemap: 'inline',
    preserveModules: true
  },
  plugins: [
    nodeResolve({ preferBuiltins: true }),
    commonjs({
      dynamicRequireTargets: ['node_modules/nconf/lib/nconf/stores/*.js']
    }),
    json()
  ]
}

I found if i do this it makes it past this part:

if (typeof module === "object" && typeof module.exports === "object") {
  module.exports.default = module.exports.default || {}
  module.exports = Object.assign(module.exports.default, module.exports); 
}
kanadgupta commented 10 months ago

Running into the same issue — as a not-so-great workaround, I used the @rollup/plugin-replace plugin to fix up that patch of code with the changes in https://github.com/JS-DevTools/ono/pull/20 and I'm no longer seeing runtime errors:

import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';
import { defineConfig } from 'rollup';

export default defineConfig({
  input: 'input.js',
  output: { file: 'output.cjs', format: 'cjs' },
  plugins: [
    commonjs(),
    json(),
    nodeResolve({ preferBuiltins: true }),
    replace({
      delimiters: ['', ''],
      preventAssignment: true,
      values: {
        'if (typeof module === "object" && typeof module.exports === "object") {':
          'if (typeof module === "object" && typeof module.exports === "object" && typeof module.exports.default === "object") {',
      },
    }),
  ],
});