ghostdevv / rollup-obfuscator

A plugin to obfuscate javascript for rollup based on https://www.npmjs.com/javascript-obfuscator
MIT License
55 stars 7 forks source link

Problem with Vite's `import.meta.env.DEV` #144

Closed raphaelmenges closed 1 year ago

raphaelmenges commented 1 year ago

Hello 👋

I am using rollup-obfuscator in combination with Vite and Electron. When upgrading from version 3.0.2 to 4.0.0 I was prompted with the following error:

TypeError: Cannot read properties of undefined (reading 'DEV')
    at Object.<anonymous> (app/packages/main/dist/index.cjs:44:83)

The corresponding line in index.cjs starts like following:

const PROD_URL_ALIAS = "local", ALLOWED_ORIGINS_AND_PERMISSIONS = new Map((void 0)["DEV"] && (void 0)["VITE_DEV_SERVER_URL"]...

I assume it has something to do with how import.meta.env.DEV of Vite is obfuscated. According to the docs of Vite, import.meta.env should not be accessed with array brackets. I guess some default in rollup-obfuscator or its dependencies was changed, such that it transforms import.meta.env.DEV differently than before?

ghostdevv commented 1 year ago

I can take a look into this later this week but at a guess it's running before vite is doing it's import.meta.env replacements, which is wrong

raphaelmenges commented 1 year ago

I have reproduced the issue using a popular vite+electron template in minimal fashion: https://github.com/raphaelmenges/rollup-obfuscator-bug

With rollup-obfuscator in version 3.0.2 it works, with rollup-obfuscator in version 4.0.0 the error is thrown upon npm run watch.

raphaelmenges commented 1 year ago

I could fix it when importing it in Vite as following:

plugins: [
  {
    ...obfuscator({
      sourceMap: process.env.MODE === 'development',
      exclude: ['./node_modules/**/*'],
      target: 'node',
    }),
    enforce: 'post',
  },
  ...
],

See the Vite documentation for more information about the enforce setting. I am not sure whether such option can be set in an rollup-plugin, or whether one would need a vite-plugin.

ghostdevv commented 1 year ago

@raphaelmenges that's a great find! Do you want to send over a PR? I don't imagine it'll cause any issues with rollup. If you do a pr you can check this by doing pnpm dev in the repo and check for errors, as that runs the rollup dev environment.

ghostdevv commented 1 year ago

It might also be ideal if we add apply: 'build', as it's pointless running in dev - I don't believe either would be considered a breaking change but worth documenting in the README nonetheless