vercel / next.js

The React Framework
https://nextjs.org
MIT License
127k stars 26.99k forks source link

DefinePlugin doesn't work for CJS code #20906

Closed hipstersmoothie closed 1 year ago

hipstersmoothie commented 3 years ago

What version of Next.js are you using?

10.0.5

What version of Node.js are you using?

12

What browser are you using?

chrome

What operating system are you using?

macOs

How are you deploying your application?

gh-pages

Describe the Bug

I have a package (next-ignite that uses variables that are defined using webpack.DefinePlugin.

next.config.js:

module.exports = (nextConfig = {}) => ({
  webpack: (config, { webpack }) => {
    config.plugins.push(
      new webpack.DefinePlugin({
        SOME_CONSTANT: "'it worked!'",
      })
    );

    // Don't clobber previous plugins' webpack functions
    if (typeof nextConfig.webpack === "function") {
      return nextConfig.webpack(config, options);
    }

    return config;
  },
});

pages/index.js:

import { test } from 'test-package';

export default function Home() {
  return (
    <div>
      {test}
    </div>
  )
}

The package is built for both CJS and ESM environments. When using SOME_CONSTANT in the package's ESM code the build works. When I try adding the main field next no longer injects SOME_CONSTANT into the code.

Expected Behavior

For DefinePlugin to work the same on CJS and ESM code.

I've made a working example just using webpack directly

To Reproduce

See a reproduction repo here

hipstersmoothie commented 3 years ago

Oddly if I switch to nextConfig.env it works but I still think this is a bug

hipstersmoothie commented 3 years ago

This seems to be the issue of wepback only running on code meant for the browser. next.js executes your code server side without webpack and client side with webpack, leading to defineplugin not being used for the server render. Odd how it works without a main field though

jankaifer commented 1 year ago

Thanks for the reproduction. It works fine in next@13.

github-actions[bot] commented 1 year ago

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.