Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ModuleNotFoundError: Module not found: Error: Can't resolve 'pnpapi' #3575

Closed
1 of 9 tasks
followbl opened this issue May 20, 2021 · 8 comments
Closed
1 of 9 tasks

ModuleNotFoundError: Module not found: Error: Can't resolve 'pnpapi' #3575

followbl opened this issue May 20, 2021 · 8 comments
Assignees
Labels
Package: nextjs Issues related to the Sentry Nextjs SDK

Comments

@followbl
Copy link

followbl commented May 20, 2021

Package + Version

  • @sentry/browser
  • @sentry/node
  • raven-js
  • raven-node (raven for node)
  • other:

Version:

"@sentry/nextjs": "6.4.1",

Description

When we include import * as Sentry from '@sentry/nextjs' anywhere within the app - it throws this ModuleNotFoundError: Module not found: Error: Can't resolve 'pnpapi' this error on build yarn run build - FWIW - we are still on webpack4

@AbhiPrasad
Copy link
Member

Hey thank you for opening an issue!

I was not able to reproduce this. I ran this with existing projects as well as tested creating new projects with the following script:

#!/bin/bash
npx create-next-app -e with-sentry next-app-with-sentry
cd next-app-with-sentry || exit
yarn add @sentry/nextjs
echo -e "import * as Sentry from '@sentry/nextjs'\n$(cat pages/index.js)" > pages/index.js
cat pages/index.js
rm -rf sentry.properties
// build runs with no error
yarn run build

Could you give us some more details on your setup? What version of nextjs are you running? Do you have a custom config, and if so could you share some more details about that?

@followbl
Copy link
Author

hey @AbhiPrasad thanks for taking a look. Below is a full next.config.js - After spending 8 hours on this yesterday I have to say - I'm a bit befuddled on this one. We're also running the most recent version of next 10.2.2

const { withSentryConfig } = require('@sentry/nextjs');
const { createSecureHeaders } = require('next-secure-headers');
const SriPlugin = require('webpack-subresource-integrity');
const DOMAIN_NAME =
  process.env.NODE_ENV === 'production'
    ? 'website'
    : process.env.DOCKER_DEV_HOST || 'localhost';

const API_BASE_HOST =
  process.env.NODE_ENV === 'production' ? `api.${DOMAIN_NAME}.com` : `${DOMAIN_NAME}:8080`;

// In production the API is at the same URL, in development it's at a different port
const API_URI = `http${
  process.env.NODE_ENV === 'production' ? 's' : ''
}://${API_BASE_HOST}/v1/graphql`;
const SUBSCRIPTION_URI = `ws${
  process.env.NODE_ENV === 'production' ? 's' : ''
}://${API_BASE_HOST}/v1/graphql`;

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});
const { NODE_ENV, TEST_CI, DOCKER_DEV_HOST } = process.env;

const basePath = '';
const releaseDate = new Date();
const DATE_STRING = releaseDate.toISOString();

const SAFE_LIST = [
  'https://assets.website.com',
];

const SentryWebpackPluginOptions = {
  ...(process.env.NODE_ENV === 'production' && {
    release: `${process?.env?.GIT_SHA}` || DATE_STRING,
  }),

  // Additional config options for the Sentry Webpack plugin. Keep in mind that
  // the following options are set automatically, and overriding them is not
  // recommended:
  //   release, url, org, project, authToken, configFile, stripPrefix,
  //   urlPrefix, include, ignore
  // For all available options, see:
  // https://github.com/getsentry/sentry-webpack-plugin#options.
};

const nextJsConfig = {
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: createSecureHeaders({
          contentSecurityPolicy: {
            directives: {
              defaultSrc: [
                "'self'",
                "'unsafe-inline'",
                "'unsafe-eval'",
                `${API_URI}`,
                `${SUBSCRIPTION_URI}`,
                ...SAFE_LIST,
              ],
              styleSrc: ["'self'", "'unsafe-inline'", ...SAFE_LIST],
              fontSrc: ["'self'", 'data:', ...SAFE_LIST],
              frameSrc: SAFE_LIST,
              imgSrc: ["'self'", 'data:', ...SAFE_LIST],
              baseUri: 'self',
              formAction: 'self',
              frameAncestors: true,
            },
          },
          frameGuard: 'deny',
          noopen: 'noopen',
          nosniff: 'nosniff',
          xssProtection: 'sanitize',
          forceHTTPSRedirect: [true, { maxAge: 60 * 60 * 24 * 360, includeSubDomains: true }],
          referrerPolicy: 'same-origin',
        }),
      },
    ];
  },
  env: {
    ciEnvironment: TEST_CI,
    // Make the COMMIT_SHA available to the client so that Sentry events can be
    // marked for the release the belong to. It may be undefined if running
    // outside of Vercel
    RELEASE_ID: `${process?.env?.GIT_SHA}` || DATE_STRING,
    DOCKER_DEV_HOST,
  },
  images: {
    domains: ['assets.website.com'],
  },
  reactStrictMode: true,
  experimental: {
    async rewrites() {
      return [
        {
          source: '/.well-known/apple-developer-merchantid-domain-association',
          destination: '/static/apple-developer-merchantid-domain-association',
        },
      ];
    },
  },
  target: 'serverless',
  webpack: (config, options) => {
    if (!options.dev && options.isServer) {
      // we're in build mode so enable shared caching for the GitHub API
      process.env.USE_CACHE = 'true';
    }

    config.plugins.push(
      new options.webpack.IgnorePlugin({
        resourceRegExp: /^pg-native$/,
      })
    );

    if (!TEST_CI && NODE_ENV === 'production') {
      config.output.crossOriginLoading = 'anonymous';
      config.plugins.push(
        new SriPlugin({
          hashFuncNames: ['sha256', 'sha384'],
          enabled: process.env.NODE_ENV === 'production',
        })
      );
    }

    return config;
  },
  basePath,
};

module.exports = withBundleAnalyzer(withSentryConfig(nextJsConfig, SentryWebpackPluginOptions));

@AbhiPrasad
Copy link
Member

AbhiPrasad commented May 26, 2021

Hey @followbl, thanks for the detailed config. It seems the issue is related to the target: serverless in your webpack config. It seems that Vercel folks prefer the experimental-serverless-trace target over theserverless target. Vercel Now also uses experimental-serverless-trace now from what I see.

See the PR adding experimental-serverless-trace to the nextjs repo for more details around this.

Could you try replacing the serverless target with experimental-serverless-trace and seeing if the build errors still occur? This fixes it on our end.

diff --git a/next.config.js b/next.config.js
index 98944a6..72dfa74 100644
--- a/next.config.js
+++ b/next.config.js
@@ -101,7 +101,7 @@ const nextJsConfig = {
       ];
     },
   },
-  target: 'serverless',
+  target: 'experimental-serverless-trace',
   webpack: (config, options) => {
     if (!options.dev && options.isServer) {
       // we're in build mode so enable shared caching for the GitHub API

If the serverless target is required for your setup, please let us know and we can continue investigating, but the experimental-serverless-trace target should cover all the use cases.

@markbrocato
Copy link

I was having the same issue and using target: 'experimental-serverless-trace' fixed it. Then, however, a new issue arose, which seems to be related to building a service worker with workbox via the nextOffline plugin. Here's the error:

Failed to compile.

You must provide the URL of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer

And here's a link to the repo so you can reproduce it: https://github.com/moovweb/next-sentry-test

@followbl
Copy link
Author

@AbhiPrasad - incredibly grateful that you were able to find out what it was. We've removed target completely and it's working fine.

this issue was raised right here and I believe should be addressed. vercel/next.js#20790

I was an early adopter of the serverless target - never saw that serverless-trace was introduced and THEN, didn't know that it was recommended to remove the target all together if it was possible for your use-case. I follow the nextjs release docs pretty closely and I didn't see this. The issue you found @AbhiPrasad solved at least 3 other issues in our application with upgrades - so very grateful for you findings.

One final related to this plugin - but unrelated to this ticket @AbhiPrasad. The sentry dev plugin is incredibly noisy, so I enabled this...with that said, other than to check the configuration that it's working every once in a while - I don't really want/need it to run locally - even though the configuration is there. What is the recommended way to programmatically disable the plugin? i.e. process.env.NODE_ENV === 'development

const SentryWebpackPluginOptions = {
  // Additional config options for the Sentry Webpack plugin. Keep in mind that
  // the following options are set automatically, and overriding them is not
  // recommended:
  //   release, url, org, project, authToken, configFile, stripPrefix,
  //   urlPrefix, include, ignore

  silent: true, // Suppresses all logs
  // For all available options, see:
  // https://github.com/getsentry/sentry-webpack-plugin#options.
};

@AbhiPrasad
Copy link
Member

Hey great to hear that this was solved for you @followbl. We really appreciated the details, and this issue ended up unblocking some other Sentry users as well, so cheers!

One final related to this plugin - but unrelated to this ticket @AbhiPrasad. The sentry dev plugin is incredibly noisy, so I enabled this...with that said, other than to check the configuration that it's working every once in a while - I don't really want/need it to run locally - even though the configuration is there. What is the recommended way to programmatically disable the plugin? i.e. process.env.NODE_ENV === 'development

We leverage our Webpack plugin under the hood, https://github.com/getsentry/sentry-webpack-plugin. To disable the plugin you can set dryRun: true. Another options is to conditionally include withSentryConfig using something like https://www.npmjs.com/package/next-compose-plugins. Btw, we totally hear you on the noise in the dev console, in fact we now set silent: true as default in our docs https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#extend-default-webpack-usage :)

I am marking this as resolved, but @markbrocato I will open another issue with your bug.

@ani4aniket
Copy link

@AbhiPrasad, Thanks for the solution, changing the target to experimental-serverless-trace works but if the project is deployed on Netlify failed while running netlify build. Hoping to get some solution.

@AbhiPrasad
Copy link
Member

@ani4aniket Thanks for letting us know. Mind opening another GH issue with your next config + Netlify build logs so we can debug?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Package: nextjs Issues related to the Sentry Nextjs SDK
Projects
None yet
Development

No branches or pull requests

5 participants