solana-labs / solana-program-library

A collection of Solana programs maintained by Solana Labs
https://solanalabs.com
Apache License 2.0
3.57k stars 2.08k forks source link

@solana/spl-token-swap@0.2.1 causing ESM import errors #3562

Closed bryantanjw closed 1 year ago

bryantanjw commented 2 years ago

Trying to use @solana/spl-token-swap package on a NextJS application but running into the error below

Error:

ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/node_modules/@solana/spl-token-swap/dist/esm/package.json' 
contains "type": "module". 
To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

Dependencies:

"@solana/spl-token": "^0.3.4",
"@solana/spl-token-swap": "^0.2.1",
jordaaash commented 2 years ago

Token Swap probably needs to get the same treatment as #3508, #3529, #3543

It seems like there was probably a change in Next.js recently that caused ESM imports to be more strict.

aneopsy commented 2 years ago

Hey, I have the same issue, any solution ?

bryantanjw commented 2 years ago

@aneopsy Try adding this line in your config.js. I'm using Next.js so this is in my next.config.js file

const nextConfig = {
  reactStrictMode: true,
  webpack: (config, { isServer }) => {
      config.resolve.fallback = {
          "@solana/spl-token-swap": require.resolve("@solana/spl-token-swap"), // <-- this line
          crypto: false,
          stream: false,
      }

      return config
  },
}

Let me know if it works

aneopsy commented 2 years ago

Hello @bryantanjw, thank you for your help, I tested to add your line but it didn't work. I finally found a solution about this problem by using next-transpile-modules:

const withTM = require('next-transpile-modules')([
  '@blocto/sdk',
  '@project-serum/sol-wallet-adapter',
  '@solana/wallet-adapter-base',
  '@solana/wallet-adapter-react',
  '@solana/wallet-adapter-wallets',
  '@solana/wallet-adapter-bitpie',
  '@solana/wallet-adapter-blocto',
  '@solana/wallet-adapter-clover',
  '@solana/wallet-adapter-coin98',
  '@solana/wallet-adapter-ledger',
  '@solana/wallet-adapter-mathwallet',
  '@solana/wallet-adapter-phantom',
  '@solana/wallet-adapter-safepal',
  '@solana/wallet-adapter-slope',
  '@solana/wallet-adapter-solflare',
  '@solana/wallet-adapter-sollet',
  '@solana/wallet-adapter-solong',
  '@solana/wallet-adapter-torus',
  '@solana/spl-token-swap',
]);

/** @type {import('next').NextConfig} */
module.exports = withTM({
  reactStrictMode: true,
  experimental: { browsersListForSwc: true, legacyBrowsers: false },
  webpack: (config, { isServer }) => {
    config.resolve.fallback = {
      crypto: false,
      stream: false,
      fs: false,
    };

    return config;
  },
});