ono icon indicating copy to clipboard operation
ono copied to clipboard

Weird CJS module hack is bombing Rollup builds

Open Prophet32j opened this issue 2 years ago • 2 comments

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); 
}

Prophet32j avatar May 17 '23 18:05 Prophet32j

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") {',
      },
    }),
  ],
});

kanadgupta avatar Sep 14 '23 15:09 kanadgupta