next.js icon indicating copy to clipboard operation
next.js copied to clipboard

fix(next-config-ts): properly handle ESM

Open devjiwonchoi opened this issue 1 year ago • 8 comments

Why?

How?

When the project is Native ESM (package.json type: "module") or used next.config.mts, we register a custom loader to resolve the ESM behaviors.

Expected

  • [ ] top-level await
  • [ ] dynamic import

Fixes #67765

devjiwonchoi avatar Jul 31 '24 16:07 devjiwonchoi

This stack of pull requests is managed by Graphite. Learn more about stacking.

devjiwonchoi avatar Jul 31 '24 16:07 devjiwonchoi

Failing test suites

Commit: e84ba51b89f65d102ebce6d85e1605d89a91d85d

pnpm test-dev test/development/acceptance-app/ReactRefreshLogBox.test.ts

  • ReactRefreshLogBox app default > server component can recover from error thrown in the module
Expand output

● ReactRefreshLogBox app default › server component can recover from error thrown in the module

Expected Redbox but found none

  1078 |
  1079 |       await next.patchFile('index.js', "throw new Error('module error')")
> 1080 |       await session.assertHasRedbox()
       |       ^
  1081 |       await next.patchFile(
  1082 |         'index.js',
  1083 |         'export default function Page() {return <p>hello world</p>}'

  at Object.<anonymous> (development/acceptance-app/ReactRefreshLogBox.test.ts:1080:7)

Read more about building and testing Next.js in contributing.md.

pnpm test-deploy test/e2e/app-dir/next-config-mts/import-json/next-config-mts.test.ts

  • next-config-ts - import json (next.config.mts) > should support import json (next.config.mts)
Expand output

● next-config-ts - import json (next.config.mts) › should support import json (next.config.mts)

Failed to deploy project https://vtest314-e2e-tests-j2dzq419e-vtest314-next-e2e-tests.vercel.app Vercel CLI 37.4.2
Retrieving project…
Deploying vtest314-next-e2e-tests/vtest314-e2e-tests
Inspect: https://vercel.com/vtest314-next-e2e-tests/vtest314-e2e-tests/SCrAo9A6XMJxq8iqMtDjiwVqpDTt [2s]
Preview: https://vtest314-e2e-tests-j2dzq419e-vtest314-next-e2e-tests.vercel.app [2s]
Queued
Building
Error: Command "npm run build" exited with 1
Error: Check your logs at https://vtest314-e2e-tests-j2dzq419e-vtest314-next-e2e-tests.vercel.app/_logs or run `vercel logs vtest314-e2e-tests-j2dzq419e-vtest314-next-e2e-tests.vercel.app` (1)

  124 |
  125 |     if (deployRes.exitCode !== 0) {
> 126 |       throw new Error(
      |             ^
  127 |         `Failed to deploy project ${deployRes.stdout} ${deployRes.stderr} (${deployRes.exitCode})`
  128 |       )
  129 |     }

  at NextDeployInstance.setup (lib/next-modes/next-deploy.ts:126:13)
  at lib/e2e-utils/index.ts:201:7
  at Span.traceAsyncFn (../packages/next/src/trace/trace.ts:143:14)
  at createNext (lib/e2e-utils/index.ts:166:12)
  at Object.<anonymous> (lib/e2e-utils/index.ts:255:14)

Read more about building and testing Next.js in contributing.md.

pnpm test-deploy test/e2e/app-dir/next-config-ts/import-json/project-esm.test.ts

  • next-config-ts - import-json (project ESM) > should support import json (project ESM)
Expand output

● next-config-ts - import-json (project ESM) › should support import json (project ESM)

Failed to deploy project https://vtest314-e2e-tests-cm9rx103a-vtest314-next-e2e-tests.vercel.app Vercel CLI 37.4.0
Retrieving project…
Deploying vtest314-next-e2e-tests/vtest314-e2e-tests
Inspect: https://vercel.com/vtest314-next-e2e-tests/vtest314-e2e-tests/fYc6geRbeXH2vbKAzu3vHQADZiff [2s]
Preview: https://vtest314-e2e-tests-cm9rx103a-vtest314-next-e2e-tests.vercel.app [2s]
Queued
Building
Error: Command "npm run build" exited with 1
Error: Check your logs at https://vtest314-e2e-tests-cm9rx103a-vtest314-next-e2e-tests.vercel.app/_logs or run `vercel logs vtest314-e2e-tests-cm9rx103a-vtest314-next-e2e-tests.vercel.app` (1)

  124 |
  125 |     if (deployRes.exitCode !== 0) {
> 126 |       throw new Error(
      |             ^
  127 |         `Failed to deploy project ${deployRes.stdout} ${deployRes.stderr} (${deployRes.exitCode})`
  128 |       )
  129 |     }

  at NextDeployInstance.setup (lib/next-modes/next-deploy.ts:126:13)
  at lib/e2e-utils/index.ts:201:7
  at Span.traceAsyncFn (../packages/next/src/trace/trace.ts:143:14)
  at createNext (lib/e2e-utils/index.ts:166:12)
  at Object.<anonymous> (lib/e2e-utils/index.ts:255:14)

Read more about building and testing Next.js in contributing.md.

ijjk avatar Jul 31 '24 16:07 ijjk

Stats from current PR

Default Build (Increase detected ⚠️)
General
vercel/next.js canary vercel/next.js 08-01-test_add_dynamic_import Change
buildDuration 21.5s 24.2s ⚠️ +2.7s
buildDurationCached 17.2s 16.6s N/A
nodeModulesSize 405 MB 403 MB N/A
nextStartRea..uration (ms) 520ms 506ms N/A
Client Bundles (main, webpack)
vercel/next.js canary vercel/next.js 08-01-test_add_dynamic_import Change
0b69cffb-HASH.js gzip 52.6 kB 52.6 kB N/A
1924.HASH.js gzip 169 B 169 B
195-HASH.js gzip 48.8 kB 45.8 kB N/A
8589-HASH.js gzip 5.27 kB 5.27 kB N/A
framework-HASH.js gzip 57.4 kB 57.4 kB N/A
main-app-HASH.js gzip 232 B 229 B N/A
main-HASH.js gzip 33.1 kB 33.2 kB N/A
webpack-HASH.js gzip 1.71 kB 1.71 kB N/A
Overall change 169 B 169 B
Legacy Client Bundles (polyfills)
vercel/next.js canary vercel/next.js 08-01-test_add_dynamic_import Change
polyfills-HASH.js gzip 39.4 kB 39.4 kB
Overall change 39.4 kB 39.4 kB
Client Pages Overall increase ⚠️
vercel/next.js canary vercel/next.js 08-01-test_add_dynamic_import Change
_app-HASH.js gzip 193 B 193 B
_error-HASH.js gzip 192 B 190 B N/A
amp-HASH.js gzip 510 B 510 B
css-HASH.js gzip 341 B 343 B N/A
dynamic-HASH.js gzip 1.84 kB 1.84 kB N/A
edge-ssr-HASH.js gzip 266 B 266 B
head-HASH.js gzip 362 B 364 B N/A
hooks-HASH.js gzip 393 B 392 B N/A
image-HASH.js gzip 4.42 kB 4.41 kB N/A
index-HASH.js gzip 268 B 268 B
link-HASH.js gzip 2.34 kB 2.78 kB ⚠️ +442 B
routerDirect..HASH.js gzip 328 B 327 B N/A
script-HASH.js gzip 398 B 396 B N/A
withRouter-HASH.js gzip 325 B 322 B N/A
1afbb74e6ecf..834.css gzip 106 B 106 B
Overall change 3.69 kB 4.13 kB ⚠️ +442 B
Client Build Manifests
vercel/next.js canary vercel/next.js 08-01-test_add_dynamic_import Change
_buildManifest.js gzip 748 B 749 B N/A
Overall change 0 B 0 B
Rendered Page Sizes
vercel/next.js canary vercel/next.js 08-01-test_add_dynamic_import Change
index.html gzip 523 B 522 B N/A
link.html gzip 538 B 536 B N/A
withRouter.html gzip 520 B 517 B N/A
Overall change 0 B 0 B
Edge SSR bundle Size
vercel/next.js canary vercel/next.js 08-01-test_add_dynamic_import Change
edge-ssr.js gzip 128 kB 128 kB N/A
page.js gzip 200 kB 198 kB N/A
Overall change 0 B 0 B
Middleware size
vercel/next.js canary vercel/next.js 08-01-test_add_dynamic_import Change
middleware-b..fest.js gzip 671 B 666 B N/A
middleware-r..fest.js gzip 156 B 155 B N/A
middleware.js gzip 31 kB 31 kB N/A
edge-runtime..pack.js gzip 844 B 844 B
Overall change 844 B 844 B
Next Runtimes
vercel/next.js canary vercel/next.js 08-01-test_add_dynamic_import Change
732-experime...dev.js gzip 322 B 322 B
732.runtime.dev.js gzip 314 B 314 B
app-page-exp...dev.js gzip 323 kB 320 kB N/A
app-page-exp..prod.js gzip 125 kB 123 kB N/A
app-page-tur..prod.js gzip 138 kB 136 kB N/A
app-page-tur..prod.js gzip 133 kB 131 kB N/A
app-page.run...dev.js gzip 314 kB 310 kB N/A
app-page.run..prod.js gzip 121 kB 119 kB N/A
app-route-ex...dev.js gzip 36.1 kB 36 kB N/A
app-route-ex..prod.js gzip 24.4 kB 24.4 kB N/A
app-route-tu..prod.js gzip 24.4 kB 24.4 kB N/A
app-route-tu..prod.js gzip 24.2 kB 24.2 kB N/A
app-route.ru...dev.js gzip 37.7 kB 37.6 kB N/A
app-route.ru..prod.js gzip 24.2 kB 24.2 kB N/A
pages-api-tu..prod.js gzip 9.57 kB 9.59 kB N/A
pages-api.ru...dev.js gzip 11.4 kB 11.4 kB N/A
pages-api.ru..prod.js gzip 9.56 kB 9.58 kB N/A
pages-turbo...prod.js gzip 21 kB 20.9 kB N/A
pages.runtim...dev.js gzip 26.6 kB 26.5 kB N/A
pages.runtim..prod.js gzip 21 kB 20.9 kB N/A
server.runti..prod.js gzip 916 kB 916 kB N/A
Overall change 636 B 636 B
build cache
vercel/next.js canary vercel/next.js 08-01-test_add_dynamic_import Change
0.pack gzip 2.03 MB 2.01 MB N/A
index.pack gzip 147 kB 146 kB N/A
Overall change 0 B 0 B
Diff details
Diff for page.js

Diff too large to display

Diff for middleware.js

Diff too large to display

Diff for edge-ssr.js

Diff too large to display

Diff for image-HASH.js
@@ -1,7 +1,7 @@
 (self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([
   [2983],
   {
-    /***/ 6745: /***/ (
+    /***/ 7391: /***/ (
       __unused_webpack_module,
       __unused_webpack_exports,
       __webpack_require__
@@ -9,7 +9,7 @@
       (window.__NEXT_P = window.__NEXT_P || []).push([
         "/image",
         function () {
-          return __webpack_require__(5675);
+          return __webpack_require__(1489);
         },
       ]);
       if (false) {
@@ -18,7 +18,7 @@
       /***/
     },
 
-    /***/ 9053: /***/ (module, exports, __webpack_require__) => {
+    /***/ 9313: /***/ (module, exports, __webpack_require__) => {
       "use strict";
       /* __next_internal_client_entry_do_not_use__  cjs */
       Object.defineProperty(exports, "__esModule", {
@@ -40,17 +40,17 @@
         __webpack_require__(6093)
       );
       const _head = /*#__PURE__*/ _interop_require_default._(
-        __webpack_require__(8808)
+        __webpack_require__(7964)
       );
-      const _getimgprops = __webpack_require__(1945);
-      const _imageconfig = __webpack_require__(7668);
-      const _imageconfigcontextsharedruntime = __webpack_require__(1694);
-      const _warnonce = __webpack_require__(1876);
-      const _routercontextsharedruntime = __webpack_require__(5575);
+      const _getimgprops = __webpack_require__(8821);
+      const _imageconfig = __webpack_require__(664);
+      const _imageconfigcontextsharedruntime = __webpack_require__(6418);
+      const _warnonce = __webpack_require__(7360);
+      const _routercontextsharedruntime = __webpack_require__(4203);
       const _imageloader = /*#__PURE__*/ _interop_require_default._(
-        __webpack_require__(3589)
+        __webpack_require__(2489)
       );
-      const _usemergedref = __webpack_require__(6746);
+      const _usemergedref = __webpack_require__(2454);
       // This is replaced by webpack define plugin
       const configEnv = {
         deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
@@ -371,7 +371,7 @@
       /***/
     },
 
-    /***/ 6746: /***/ (module, exports, __webpack_require__) => {
+    /***/ 2454: /***/ (module, exports, __webpack_require__) => {
       "use strict";
 
       Object.defineProperty(exports, "__esModule", {
@@ -432,7 +432,7 @@
       /***/
     },
 
-    /***/ 1945: /***/ (
+    /***/ 8821: /***/ (
       __unused_webpack_module,
       exports,
       __webpack_require__
@@ -448,9 +448,9 @@
           return getImgProps;
         },
       });
-      const _warnonce = __webpack_require__(1876);
-      const _imageblursvg = __webpack_require__(6704);
-      const _imageconfig = __webpack_require__(7668);
+      const _warnonce = __webpack_require__(7360);
+      const _imageblursvg = __webpack_require__(5884);
+      const _imageconfig = __webpack_require__(664);
       const VALID_LOADING_VALUES =
         /* unused pure expression or super */ null && [
           "lazy",
@@ -726,8 +726,8 @@
         }
         if (
           isDefaultLoader &&
-          !config.dangerouslyAllowSVG &&
-          src.split("?", 1)[0].endsWith(".svg")
+          src.endsWith(".svg") &&
+          !config.dangerouslyAllowSVG
         ) {
           // Special case to make svg serve as-is to avoid proxying
           // through the built-in Image Optimization API.
@@ -824,7 +824,7 @@
       /***/
     },
 
-    /***/ 6704: /***/ (__unused_webpack_module, exports) => {
+    /***/ 5884: /***/ (__unused_webpack_module, exports) => {
       "use strict";
       /**
        * A shared function, used on both client and server, to generate a SVG blur placeholder.
@@ -879,7 +879,7 @@
       /***/
     },
 
-    /***/ 965: /***/ (
+    /***/ 9345: /***/ (
       __unused_webpack_module,
       exports,
       __webpack_require__
@@ -906,10 +906,10 @@
         },
       });
       const _interop_require_default = __webpack_require__(1739);
-      const _getimgprops = __webpack_require__(1945);
-      const _imagecomponent = __webpack_require__(9053);
+      const _getimgprops = __webpack_require__(8821);
+      const _imagecomponent = __webpack_require__(9313);
       const _imageloader = /*#__PURE__*/ _interop_require_default._(
-        __webpack_require__(3589)
+        __webpack_require__(2489)
       );
       function getImageProps(imgProps) {
         const { props } = (0, _getimgprops.getImgProps)(imgProps, {
@@ -941,7 +941,7 @@
       /***/
     },
 
-    /***/ 3589: /***/ (__unused_webpack_module, exports) => {
+    /***/ 2489: /***/ (__unused_webpack_module, exports) => {
       "use strict";
 
       Object.defineProperty(exports, "__esModule", {
@@ -976,7 +976,7 @@
       /***/
     },
 
-    /***/ 5675: /***/ (
+    /***/ 1489: /***/ (
       __unused_webpack_module,
       __webpack_exports__,
       __webpack_require__
@@ -993,8 +993,8 @@
 
       // EXTERNAL MODULE: ./node_modules/.pnpm/[email protected]/node_modules/react/jsx-runtime.js
       var jsx_runtime = __webpack_require__(6322);
-      // EXTERNAL MODULE: ./node_modules/.pnpm/next@file+..+main-repo+packages+next+next-packed.tgz_react-dom@19.0.0-rc-380f5d67-20241113_re_d7fg766ptstyt4prarg74ol27i/node_modules/next/image.js
-      var next_image = __webpack_require__(1695);
+      // EXTERNAL MODULE: ./node_modules/.pnpm/next@file+..+diff-repo+packages+next+next-packed.tgz_react-dom@19.0.0-rc-380f5d67-20241113_re_k6jswiqskvoeqe45yhuljotqne/node_modules/next/image.js
+      var next_image = __webpack_require__(8106);
       var image_default = /*#__PURE__*/ __webpack_require__.n(next_image); // ./pages/nextjs.png
       /* harmony default export */ const nextjs = {
         src: "/_next/static/media/nextjs.cae0b805.png",
@@ -1024,12 +1024,12 @@
       /***/
     },
 
-    /***/ 1695: /***/ (
+    /***/ 8106: /***/ (
       module,
       __unused_webpack_exports,
       __webpack_require__
     ) => {
-      module.exports = __webpack_require__(965);
+      module.exports = __webpack_require__(9345);
 
       /***/
     },
@@ -1039,7 +1039,7 @@
     /******/ var __webpack_exec__ = (moduleId) =>
       __webpack_require__((__webpack_require__.s = moduleId));
     /******/ __webpack_require__.O(0, [636, 6593, 8792], () =>
-      __webpack_exec__(6745)
+      __webpack_exec__(7391)
     );
     /******/ var __webpack_exports__ = __webpack_require__.O();
     /******/ _N_E = __webpack_exports__;
Diff for link-HASH.js
@@ -1,7 +1,7 @@
 (self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([
   [4672],
   {
-    /***/ 7439: /***/ (
+    /***/ 9669: /***/ (
       __unused_webpack_module,
       __unused_webpack_exports,
       __webpack_require__
@@ -9,7 +9,7 @@
       (window.__NEXT_P = window.__NEXT_P || []).push([
         "/link",
         function () {
-          return __webpack_require__(2930);
+          return __webpack_require__(3336);
         },
       ]);
       if (false) {
@@ -18,7 +18,85 @@
       /***/
     },
 
-    /***/ 3398: /***/ (module, exports, __webpack_require__) => {
+    /***/ 6106: /***/ (module, exports) => {
+      "use strict";
+
+      Object.defineProperty(exports, "__esModule", {
+        value: true,
+      });
+      0 && 0;
+      function _export(target, all) {
+        for (var name in all)
+          Object.defineProperty(target, name, {
+            enumerable: true,
+            get: all[name],
+          });
+      }
+      _export(exports, {
+        ACTION_HMR_REFRESH: function () {
+          return ACTION_HMR_REFRESH;
+        },
+        ACTION_NAVIGATE: function () {
+          return ACTION_NAVIGATE;
+        },
+        ACTION_PREFETCH: function () {
+          return ACTION_PREFETCH;
+        },
+        ACTION_REFRESH: function () {
+          return ACTION_REFRESH;
+        },
+        ACTION_RESTORE: function () {
+          return ACTION_RESTORE;
+        },
+        ACTION_SERVER_ACTION: function () {
+          return ACTION_SERVER_ACTION;
+        },
+        ACTION_SERVER_PATCH: function () {
+          return ACTION_SERVER_PATCH;
+        },
+        PrefetchCacheEntryStatus: function () {
+          return PrefetchCacheEntryStatus;
+        },
+        PrefetchKind: function () {
+          return PrefetchKind;
+        },
+      });
+      const ACTION_REFRESH = "refresh";
+      const ACTION_NAVIGATE = "navigate";
+      const ACTION_RESTORE = "restore";
+      const ACTION_SERVER_PATCH = "server-patch";
+      const ACTION_PREFETCH = "prefetch";
+      const ACTION_HMR_REFRESH = "hmr-refresh";
+      const ACTION_SERVER_ACTION = "server-action";
+      var PrefetchKind;
+      (function (PrefetchKind) {
+        PrefetchKind["AUTO"] = "auto";
+        PrefetchKind["FULL"] = "full";
+        PrefetchKind["TEMPORARY"] = "temporary";
+      })(PrefetchKind || (PrefetchKind = {}));
+      var PrefetchCacheEntryStatus;
+      (function (PrefetchCacheEntryStatus) {
+        PrefetchCacheEntryStatus["fresh"] = "fresh";
+        PrefetchCacheEntryStatus["reusable"] = "reusable";
+        PrefetchCacheEntryStatus["expired"] = "expired";
+        PrefetchCacheEntryStatus["stale"] = "stale";
+      })(PrefetchCacheEntryStatus || (PrefetchCacheEntryStatus = {}));
+      if (
+        (typeof exports.default === "function" ||
+          (typeof exports.default === "object" && exports.default !== null)) &&
+        typeof exports.default.__esModule === "undefined"
+      ) {
+        Object.defineProperty(exports.default, "__esModule", {
+          value: true,
+        });
+        Object.assign(exports.default, exports);
+        module.exports = exports.default;
+      } //# sourceMappingURL=router-reducer-types.js.map
+
+      /***/
+    },
+
+    /***/ 2042: /***/ (module, exports, __webpack_require__) => {
       "use strict";
 
       Object.defineProperty(exports, "__esModule", {
@@ -30,7 +108,7 @@
           return getDomainLocale;
         },
       });
-      const _normalizetrailingslash = __webpack_require__(2710);
+      const _normalizetrailingslash = __webpack_require__(4922);
       const basePath =
         /* unused pure expression or super */ null && (false || "");
       function getDomainLocale(path, locale, locales, domainLocales) {
@@ -54,7 +132,7 @@
       /***/
     },
 
-    /***/ 6743: /***/ (module, exports, __webpack_require__) => {
+    /***/ 5368: /***/ (module, exports, __webpack_require__) => {
       "use strict";
       /* __next_internal_client_entry_do_not_use__  cjs */
       Object.defineProperty(exports, "__esModule", {
@@ -71,26 +149,32 @@
       const _react = /*#__PURE__*/ _interop_require_default._(
         __webpack_require__(2138)
       );
-      const _resolvehref = __webpack_require__(7894);
-      const _islocalurl = __webpack_require__(3110);
-      const _formaturl = __webpack_require__(6239);
-      const _utils = __webpack_require__(8569);
-      const _addlocale = __webpack_require__(2800);
-      const _routercontextsharedruntime = __webpack_require__(5575);
-      const _useintersection = __webpack_require__(2655);
-      const _getdomainlocale = __webpack_require__(3398);
-      const _addbasepath = __webpack_require__(7315);
-      const _usemergedref = __webpack_require__(6746);
+      const _resolvehref = __webpack_require__(8698);
+      const _islocalurl = __webpack_require__(4914);
+      const _formaturl = __webpack_require__(2827);
+      const _utils = __webpack_require__(7213);
+      const _addlocale = __webpack_require__(8764);
+      const _routercontextsharedruntime = __webpack_require__(4203);
+      const _approutercontextsharedruntime = __webpack_require__(8437);
+      const _useintersection = __webpack_require__(5347);
+      const _getdomainlocale = __webpack_require__(2042);
+      const _addbasepath = __webpack_require__(2671);
+      const _routerreducertypes = __webpack_require__(6106);
+      const _usemergedref = __webpack_require__(2454);
       const prefetched = new Set();
-      function prefetch(router, href, as, options) {
+      function prefetch(router, href, as, options, appOptions, isAppRouter) {
         if (false) {
         }
-        if (!(0, _islocalurl.isLocalURL)(href)) {
+        // app-router supports external urls out of the box so it shouldn't short-circuit here as support for e.g. `replace` is added in the app-router.
+        if (!isAppRouter && !(0, _islocalurl.isLocalURL)(href)) {
           return;
         }
         // We should only dedupe requests when experimental.optimisticClientCache is
-        // disabled.
-        if (!options.bypassPrefetchedCheck) {
+        // disabled & when we're not using the app router. App router handles
+        // reusing an existing prefetch entry (if it exists) for the same URL.
+        // If we dedupe in here, we will cause a race where different prefetch kinds
+        // to the same URL (ie auto vs true) will cause one to be ignored.
+        if (!options.bypassPrefetchedCheck && !isAppRouter) {
           const locale =
             typeof options.locale !== "undefined"
               ? options.locale
@@ -105,11 +189,20 @@
           // Mark this URL as prefetched.
           prefetched.add(prefetchedKey);
         }
+        const doPrefetch = async () => {
+          if (isAppRouter) {
+            // note that `appRouter.prefetch()` is currently sync,
+            // so we have to wrap this call in an async function to be able to catch() errors below.
+            return router.prefetch(href, appOptions);
+          } else {
+            return router.prefetch(href, as, options);
+          }
+        };
         // Prefetch the JSON page if asked (only in the client)
         // We need to handle a prefetch error here since we may be
         // loading with priority which can reject but we don't
         // want to force navigation since this is only a prefetch
-        router.prefetch(href, as, options).catch((err) => {
+        doPrefetch().catch((err) => {
           if (false) {
           }
         });
@@ -134,14 +227,16 @@
         replace,
         shallow,
         scroll,
-        locale
+        locale,
+        isAppRouter
       ) {
         const { nodeName } = e.currentTarget;
         // anchors inside an svg have a lowercase nodeName
         const isAnchorNodeName = nodeName.toUpperCase() === "A";
         if (
           isAnchorNodeName &&
-          (isModifiedEvent(e) || !(0, _islocalurl.isLocalURL)(href))
+          (isModifiedEvent(e) || // app-router supports external urls out of the box so it shouldn't short-circuit here as support for e.g. `replace` is added in the app-router.
+            (!isAppRouter && !(0, _islocalurl.isLocalURL)(href)))
         ) {
           // ignore click for browser’s default behavior
           return;
@@ -162,7 +257,11 @@
             });
           }
         };
-        navigate();
+        if (isAppRouter) {
+          _react.default.startTransition(navigate);
+        } else {
+          navigate();
+        }
       }
       function formatStringOrUrl(urlObjOrString) {
         if (typeof urlObjOrString === "string") {
@@ -205,14 +304,31 @@
               children: children,
             });
           }
-          const router = _react.default.useContext(
+          const pagesRouter = _react.default.useContext(
             _routercontextsharedruntime.RouterContext
           );
+          const appRouter = _react.default.useContext(
+            _approutercontextsharedruntime.AppRouterContext
+          );
+          const router = pagesRouter != null ? pagesRouter : appRouter;
+          // We're in the app directory if there is no pages router.
+          const isAppRouter = !pagesRouter;
           const prefetchEnabled = prefetchProp !== false;
+          /**
+           * The possible states for prefetch are:
+           * - null: this is the default "auto" mode, where we will prefetch partially if the link is in the viewport
+           * - true: we will prefetch if the link is visible and prefetch the full page, not just partially
+           * - false: we will not prefetch if in the viewport at all
+           */ const appPrefetchKind =
+            prefetchProp === null
+              ? _routerreducertypes.PrefetchKind.AUTO
+              : _routerreducertypes.PrefetchKind.FULL;
+          if (false) {
+          }
           if (false) {
           }
           const { href, as } = _react.default.useMemo(() => {
-            if (!router) {
+            if (!pagesRouter) {
               const resolvedHref = formatStringOrUrl(hrefProp);
               return {
                 href: resolvedHref,
@@ -220,17 +336,17 @@
               };
             }
             const [resolvedHref, resolvedAs] = (0, _resolvehref.resolveHref)(
-              router,
+              pagesRouter,
               hrefProp,
               true
             );
             return {
               href: resolvedHref,
               as: asProp
-                ? (0, _resolvehref.resolveHref)(router, asProp)
+                ? (0, _resolvehref.resolveHref)(pagesRouter, asProp)
                 : resolvedAs || resolvedHref,
             };
-          }, [router, hrefProp, asProp]);
+          }, [pagesRouter, hrefProp, asProp]);
           const previousHref = _react.default.useRef(href);
           const previousAs = _react.default.useRef(as);
           // This will return the first child, if multiple are provided it will throw an error
@@ -280,17 +396,28 @@
               return;
             }
             // Prefetch the URL.
-            prefetch(router, href, as, {
-              locale,
-            });
+            prefetch(
+              router,
+              href,
+              as,
+              {
+                locale,
+              },
+              {
+                kind: appPrefetchKind,
+              },
+              isAppRouter
+            );
           }, [
             as,
             href,
             isVisible,
             locale,
             prefetchEnabled,
-            router == null ? void 0 : router.locale,
+            pagesRouter == null ? void 0 : pagesRouter.locale,
             router,
+            isAppRouter,
+            appPrefetchKind,
           ]);
           const childProps = {
             ref: setRef,
@@ -321,7 +448,8 @@
                 replace,
                 shallow,
                 scroll,
-                locale
+                locale,
+                isAppRouter
               );
             },
             onMouseEnter(e) {
@@ -338,12 +466,27 @@
               if (!router) {
                 return;
               }
-              prefetch(router, href, as, {
-                locale,
-                priority: true,
-                // @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642}
-                bypassPrefetchedCheck: true,
-              });
+              if (
+                (!prefetchEnabled || "production" === "development") &&
+                isAppRouter
+              ) {
+                return;
+              }
+              prefetch(
+                router,
+                href,
+                as,
+                {
+                  locale,
+                  priority: true,
+                  // @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642}
+                  bypassPrefetchedCheck: true,
+                },
+                {
+                  kind: appPrefetchKind,
+                },
+                isAppRouter
+              );
             },
             onTouchStart: false
               ? 0
@@ -364,12 +507,24 @@
                   if (!router) {
                     return;
                   }
-                  prefetch(router, href, as, {
-                    locale,
-                    priority: true,
-                    // @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642}
-                    bypassPrefetchedCheck: true,
-                  });
+                  if (!prefetchEnabled && isAppRouter) {
+                    return;
+                  }
+                  prefetch(
+                    router,
+                    href,
+                    as,
+                    {
+                      locale,
+                      priority: true,
+                      // @see {https://github.com/vercel/next.js/discussions/40268?sort=top#discussioncomment-3572642}
+                      bypassPrefetchedCheck: true,
+                    },
+                    {
+                      kind: appPrefetchKind,
+                    },
+                    isAppRouter
+                  );
                 },
           };
           // If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is
@@ -385,18 +540,18 @@
             const curLocale =
               typeof locale !== "undefined"
                 ? locale
-                : router == null
+                : pagesRouter == null
                 ? void 0
-                : router.locale;
+                : pagesRouter.locale;
             // we only render domain locales if we are currently on a domain locale
             // so that locale links are still visitable in development/preview envs
             const localeDomain =
-              (router == null ? void 0 : router.isLocaleDomain) &&
+              (pagesRouter == null ? void 0 : pagesRouter.isLocaleDomain) &&
               (0, _getdomainlocale.getDomainLocale)(
                 as,
                 curLocale,
-                router == null ? void 0 : router.locales,
-                router == null ? void 0 : router.domainLocales
+                pagesRouter == null ? void 0 : pagesRouter.locales,
+                pagesRouter == null ? void 0 : pagesRouter.domainLocales
               );
             childProps.href =
               localeDomain ||
@@ -404,7 +559,7 @@
                 (0, _addlocale.addLocale)(
                   as,
                   curLocale,
-                  router == null ? void 0 : router.defaultLocale
+                  pagesRouter == null ? void 0 : pagesRouter.defaultLocale
                 )
               );
           }
@@ -433,7 +588,7 @@
       /***/
     },
 
-    /***/ 2655: /***/ (module, exports, __webpack_require__) => {
+    /***/ 5347: /***/ (module, exports, __webpack_require__) => {
       "use strict";
 
       Object.defineProperty(exports, "__esModule", {
@@ -446,7 +601,7 @@
         },
       });
       const _react = __webpack_require__(2138);
-      const _requestidlecallback = __webpack_require__(484);
+      const _requestidlecallback = __webpack_require__(7368);
       const hasIntersectionObserver =
         typeof IntersectionObserver === "function";
       const observers = new Map();
@@ -559,7 +714,7 @@
       /***/
     },
 
-    /***/ 6746: /***/ (module, exports, __webpack_require__) => {
+    /***/ 2454: /***/ (module, exports, __webpack_require__) => {
       "use strict";
 
       Object.defineProperty(exports, "__esModule", {
@@ -620,7 +775,7 @@
       /***/
     },
 
-    /***/ 2930: /***/ (
+    /***/ 3336: /***/ (
       __unused_webpack_module,
       __webpack_exports__,
       __webpack_require__
@@ -635,7 +790,7 @@
       /* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ =
         __webpack_require__(6322);
       /* harmony import */ var next_link__WEBPACK_IMPORTED_MODULE_1__ =
-        __webpack_require__(6661);
+        __webpack_require__(3627);
       /* harmony import */ var next_link__WEBPACK_IMPORTED_MODULE_1___default =
         /*#__PURE__*/ __webpack_require__.n(
           next_link__WEBPACK_IMPORTED_MODULE_1__
@@ -666,12 +821,12 @@
       /***/
     },
 
-    /***/ 6661: /***/ (
+    /***/ 3627: /***/ (
       module,
       __unused_webpack_exports,
       __webpack_require__
     ) => {
-      module.exports = __webpack_require__(6743);
+      module.exports = __webpack_require__(5368);
 
       /***/
     },
@@ -681,7 +836,7 @@
     /******/ var __webpack_exec__ = (moduleId) =>
       __webpack_require__((__webpack_require__.s = moduleId));
     /******/ __webpack_require__.O(0, [636, 6593, 8792], () =>
-      __webpack_exec__(7439)
+      __webpack_exec__(9669)
     );
     /******/ var __webpack_exports__ = __webpack_require__.O();
     /******/ _N_E = __webpack_exports__;
Diff for 195-HASH.js

Diff too large to display

Diff for 8589-HASH.js
@@ -1,8 +1,8 @@
 "use strict";
 (self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([
-  [8589],
+  [943],
   {
-    /***/ 8589: /***/ (module, exports, __webpack_require__) => {
+    /***/ 943: /***/ (module, exports, __webpack_require__) => {
       /* __next_internal_client_entry_do_not_use__  cjs */
       Object.defineProperty(exports, "__esModule", {
         value: true,
@@ -13,27 +13,27 @@
           return Image;
         },
       });
-      const _interop_require_default = __webpack_require__(3734);
-      const _interop_require_wildcard = __webpack_require__(8367);
-      const _jsxruntime = __webpack_require__(7682);
+      const _interop_require_default = __webpack_require__(5322);
+      const _interop_require_wildcard = __webpack_require__(1131);
+      const _jsxruntime = __webpack_require__(6420);
       const _react = /*#__PURE__*/ _interop_require_wildcard._(
-        __webpack_require__(6442)
+        __webpack_require__(9864)
       );
       const _reactdom = /*#__PURE__*/ _interop_require_default._(
-        __webpack_require__(7191)
+        __webpack_require__(5401)
       );
       const _head = /*#__PURE__*/ _interop_require_default._(
-        __webpack_require__(3510)
+        __webpack_require__(612)
       );
-      const _getimgprops = __webpack_require__(8685);
-      const _imageconfig = __webpack_require__(58);
-      const _imageconfigcontextsharedruntime = __webpack_require__(5846);
-      const _warnonce = __webpack_require__(2268);
-      const _routercontextsharedruntime = __webpack_require__(647);
+      const _getimgprops = __webpack_require__(7579);
+      const _imageconfig = __webpack_require__(9704);
+      const _imageconfigcontextsharedruntime = __webpack_require__(8632);
+      const _warnonce = __webpack_require__(9622);
+      const _routercontextsharedruntime = __webpack_require__(5373);
       const _imageloader = /*#__PURE__*/ _interop_require_default._(
-        __webpack_require__(9431)
+        __webpack_require__(2481)
       );
-      const _usemergedref = __webpack_require__(6412);
+      const _usemergedref = __webpack_require__(6854);
       // This is replaced by webpack define plugin
       const configEnv = {
         deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
@@ -355,7 +355,7 @@
       /***/
     },
 
-    /***/ 6412: /***/ (module, exports, __webpack_require__) => {
+    /***/ 6854: /***/ (module, exports, __webpack_require__) => {
       Object.defineProperty(exports, "__esModule", {
         value: true,
       });
@@ -365,7 +365,7 @@
           return useMergedRef;
         },
       });
-      const _react = __webpack_require__(6442);
+      const _react = __webpack_require__(9864);
       function useMergedRef(refA, refB) {
         const cleanupA = (0, _react.useRef)(() => {});
         const cleanupB = (0, _react.useRef)(() => {});
@@ -414,7 +414,7 @@
       /***/
     },
 
-    /***/ 7034: /***/ (
+    /***/ 9176: /***/ (
       __unused_webpack_module,
       exports,
       __webpack_require__
@@ -428,9 +428,9 @@
           return AmpStateContext;
         },
       });
-      const _interop_require_default = __webpack_require__(3734);
+      const _interop_require_default = __webpack_require__(5322);
       const _react = /*#__PURE__*/ _interop_require_default._(
-        __webpack_require__(6442)
+        __webpack_require__(9864)
       );
       const AmpStateContext = _react.default.createContext({});
       if (false) {
@@ -439,7 +439,7 @@
       /***/
     },
 
-    /***/ 558: /***/ (__unused_webpack_module, exports) => {
+    /***/ 2272: /***/ (__unused_webpack_module, exports) => {
       Object.defineProperty(exports, "__esModule", {
         value: true,
       });
@@ -461,7 +461,7 @@
       /***/
     },
 
-    /***/ 8685: /***/ (
+    /***/ 7579: /***/ (
       __unused_webpack_module,
       exports,
       __webpack_require__
@@ -475,9 +475,9 @@
           return getImgProps;
         },
       });
-      const _warnonce = __webpack_require__(2268);
-      const _imageblursvg = __webpack_require__(6950);
-      const _imageconfig = __webpack_require__(58);
+      const _warnonce = __webpack_require__(9622);
+      const _imageblursvg = __webpack_require__(3780);
+      const _imageconfig = __webpack_require__(9704);
       const VALID_LOADING_VALUES =
         /* unused pure expression or super */ null && [
           "lazy",
@@ -753,8 +753,8 @@
         }
         if (
           isDefaultLoader &&
-          !config.dangerouslyAllowSVG &&
-          src.split("?", 1)[0].endsWith(".svg")
+          src.endsWith(".svg") &&
+          !config.dangerouslyAllowSVG
         ) {
           // Special case to make svg serve as-is to avoid proxying
           // through the built-in Image Optimization API.
@@ -851,8 +851,8 @@
       /***/
     },
 
-    /***/ 3510: /***/ (module, exports, __webpack_require__) => {
-      /* provided dependency */ var process = __webpack_require__(3711);
+    /***/ 612: /***/ (module, exports, __webpack_require__) => {
+      /* provided dependency */ var process = __webpack_require__(2285);
       /* __next_internal_client_entry_do_not_use__  cjs */
       Object.defineProperty(exports, "__esModule", {
         value: true,
@@ -873,19 +873,19 @@
           return defaultHead;
         },
       });
-      const _interop_require_default = __webpack_require__(3734);
-      const _interop_require_wildcard = __webpack_require__(8367);
-      const _jsxruntime = __webpack_require__(7682);
+      const _interop_require_default = __webpack_require__(5322);
+      const _interop_require_wildcard = __webpack_require__(1131);
+      const _jsxruntime = __webpack_require__(6420);
       const _react = /*#__PURE__*/ _interop_require_wildcard._(
-        __webpack_require__(6442)
+        __webpack_require__(9864)
       );
       const _sideeffect = /*#__PURE__*/ _interop_require_default._(
-        __webpack_require__(3355)
+        __webpack_require__(7965)
       );
-      const _ampcontextsharedruntime = __webpack_require__(7034);
-      const _headmanagercontextsharedruntime = __webpack_require__(1360);
-      const _ampmode = __webpack_require__(558);
-      const _warnonce = __webpack_require__(2268);
+      const _ampcontextsharedruntime = __webpack_require__(9176);
+      const _headmanagercontextsharedruntime = __webpack_require__(6038);
+      const _ampmode = __webpack_require__(2272);
+      const _warnonce = __webpack_require__(9622);
       function defaultHead(inAmpMode) {
         if (inAmpMode === void 0) inAmpMode = false;
         const head = [
@@ -1069,7 +1069,7 @@
       /***/
     },
 
-    /***/ 6950: /***/ (__unused_webpack_module, exports) => {
+    /***/ 3780: /***/ (__unused_webpack_module, exports) => {
       /**
        * A shared function, used on both client and server, to generate a SVG blur placeholder.
        */
@@ -1123,7 +1123,7 @@
       /***/
     },
 
-    /***/ 5846: /***/ (
+    /***/ 8632: /***/ (
       __unused_webpack_module,
       exports,
       __webpack_require__
@@ -1137,11 +1137,11 @@
           return ImageConfigContext;
         },
       });
-      const _interop_require_default = __webpack_require__(3734);
+      const _interop_require_default = __webpack_require__(5322);
       const _react = /*#__PURE__*/ _interop_require_default._(
-        __webpack_require__(6442)
+        __webpack_require__(9864)
       );
-      const _imageconfig = __webpack_require__(58);
+      const _imageconfig = __webpack_require__(9704);
       const ImageConfigContext = _react.default.createContext(
         _imageconfig.imageConfigDefault
       );
@@ -1151,7 +1151,7 @@
       /***/
     },
 
-    /***/ 58: /***/ (__unused_webpack_module, exports) => {
+    /***/ 9704: /***/ (__unused_webpack_module, exports) => {
       Object.defineProperty(exports, "__esModule", {
         value: true,
       });
@@ -1199,7 +1199,7 @@
       /***/
     },
 
-    /***/ 9431: /***/ (__unused_webpack_module, exports) => {
+    /***/ 2481: /***/ (__unused_webpack_module, exports) => {
       Object.defineProperty(exports, "__esModule", {
         value: true,
       });
@@ -1232,7 +1232,7 @@
       /***/
     },
 
-    /***/ 647: /***/ (
+    /***/ 5373: /***/ (
       __unused_webpack_module,
       exports,
       __webpack_require__
@@ -1246,9 +1246,9 @@
           return RouterContext;
         },
       });
-      const _interop_require_default = __webpack_require__(3734);
+      const _interop_require_default = __webpack_require__(5322);
       const _react = /*#__PURE__*/ _interop_require_default._(
-        __webpack_require__(6442)
+        __webpack_require__(9864)
       );
       const RouterContext = _react.default.createContext(null);
       if (false) {
@@ -1257,7 +1257,7 @@
       /***/
     },
 
-    /***/ 3355: /***/ (
+    /***/ 7965: /***/ (
       __unused_webpack_module,
       exports,
       __webpack_require__
@@ -1271,7 +1271,7 @@
           return SideEffect;
         },
       });
-      const _react = __webpack_require__(6442);
+      const _react = __webpack_require__(9864);
       const isServer = typeof window === "undefined";
       const useClientOnlyLayoutEffect = isServer
         ? () => {}
Diff for main-HASH.js

Diff too large to display

Diff for app-page-exp..ntime.dev.js
failed to diff
Diff for app-page-exp..time.prod.js

Diff too large to display

Diff for app-page-tur..time.prod.js

Diff too large to display

Diff for app-page-tur..time.prod.js

Diff too large to display

Diff for app-page.runtime.dev.js
failed to diff
Diff for app-page.runtime.prod.js

Diff too large to display

Diff for app-route-ex..ntime.dev.js

Diff too large to display

Diff for app-route-ex..time.prod.js

Diff too large to display

Diff for app-route-tu..time.prod.js

Diff too large to display

Diff for app-route-tu..time.prod.js

Diff too large to display

Diff for app-route.runtime.dev.js

Diff too large to display

Diff for app-route.ru..time.prod.js

Diff too large to display

Diff for pages-api-tu..time.prod.js

Diff too large to display

Diff for pages-api.runtime.dev.js

Diff too large to display

Diff for pages-api.ru..time.prod.js

Diff too large to display

Diff for pages-turbo...time.prod.js

Diff too large to display

Diff for pages.runtime.dev.js

Diff too large to display

Diff for pages.runtime.prod.js

Diff too large to display

Diff for server.runtime.prod.js
failed to diff
Commit: e84ba51b89f65d102ebce6d85e1605d89a91d85d

ijjk avatar Jul 31 '24 16:07 ijjk

This sounds amazing! 😍

I guess this will also resolve other ESM-related errors like ERR_PACKAGE_PATH_NOT_EXPORTED / No "exports" main defined when trying to import an ESM-only package like @shikijs/rehype?

From the error stack trace below, it seems like it's still using the Node.js CommonJS loader internally...

$ next build
⨯ Failed to load next.config.ts, see more info here https://nextjs.org/docs/messages/next-config-error

> Build error occurred
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /home/runner/work/courses/courses/node_modules/@shikijs/vscode-textmate/package.json
    at exportsNotFound (node:internal/modules/esm/resolve:304:10)
    at packageExportsResolve (node:internal/modules/esm/resolve:594:13)
    at resolveExports (node:internal/modules/cjs/loader:634:36)
    at Module._findPath (node:internal/modules/cjs/loader:724:31)
    at Module._resolveFilename (node:internal/modules/cjs/loader:1211:27)
    at /home/runner/work/courses/courses/node_modules/next/dist/server/require-hook.js:55:36
    at Module._load (node:internal/modules/cjs/loader:1051:27)
    at Module.require (node:internal/modules/cjs/loader:1311:19)
    at mod.require (/home/runner/work/courses/courses/node_modules/next/dist/server/require-hook.js:65:28)
    at require (node:internal/modules/helpers:179:18) {
  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}

next.config.ts

import withMDX from '@next/mdx';
import rehypeShiki from '@shikijs/rehype';
import type { NextConfig } from 'next';
// ...

const config: NextConfig = {
  reactStrictMode: true,
  experimental: {
    typedRoutes: true,
    // Remove .js from import specifiers, because Next.js and
    // webpack do not yet support TypeScript-style module
    // resolution out of the box
    // https://github.com/webpack/webpack/issues/13252#issuecomment-1171080020
    // https://github.com/vercel/next.js/pull/45423
    // https://github.com/vercel/next.js/issues/58805
    // https://github.com/vercel/next.js/issues/54550
    extensionAlias: {
      '.js': ['.ts', '.tsx', '.js', '.jsx'],
      '.jsx': ['.tsx', '.jsx'],
      '.mjs': ['.mts', '.mjs'],
      '.cjs': ['.cts', '.cjs'],
    },
  },
  pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'],
  // ...
  transpilePackages: ['@upleveled/cargobay', '@upleveled/global-config'],
  // ...
};

export default withMDX({
  options: {
    // ...
    rehypePlugins: [
      // ...
      [
        rehypeShiki,
        {
          theme: 'dark-plus',
        },
      ],
    ],
  },
})(config);

This is with this package.json from @shikijs/[email protected]:

{
  "name": "@shikijs/vscode-textmate",
  "version": "9.2.2",
  "packageManager": "[email protected]",
  "description": "Shiki's fork of `vscode-textmate`",
  "author": {
    "name": "Microsoft Corporation"
  },
  "exports": {
    ".": {
      "import": "./dist/index.mjs",
      "types": "./dist/index.d.mts"
    }
  },
  "main": "./dist/index.mjs",
  "types": "./dist/index.d.mts",
  "repository": {
    "type": "git",
    "url": "https://github.com/shikijs/vscode-textmate"
  },
  "files": [
    "dist"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/shikijs/vscode-textmate/issues"
  },
  "scripts": {
    "build": "tsup",
    "watch": "tsc --watch",
    "compile": "tsc",
    "test": "mocha --ui=tdd ./out/tests/all.test.js",
    "benchmark": "node benchmark/benchmark.js",
    "inspect": "node out/tests/inspect.js",
    "tmconvert": "node scripts/tmconvert.js",
    "version": "npm run compile && npm run test",
    "postversion": "git push && git push --tags",
    "prepublishOnly": "npm run build",
    "release": "bumpp && npm publish"
  },
  "devDependencies": {
    "@types/mocha": "^9.1.0",
    "@types/node": "^16.6.1",
    "bumpp": "^9.5.2",
    "mocha": "^9.2.2",
    "tsup": "^8.2.4",
    "typescript": "^4.3.5",
    "vscode-oniguruma": "^1.5.1"
  }
}

@devjiwonchoi Or if this is unrelated, I can also open a different issue...

karlhorky avatar Sep 18 '24 11:09 karlhorky

Also potentially related:

  • #70201

karlhorky avatar Sep 18 '24 11:09 karlhorky

@devjiwonchoi for ESM projects using "type": "module", is there currently a way to patch node_modules (before this PR lands) that would allow for this custom loader described in the PR description?

I'm ok with disabling the CommonJS behavior - this particular project is ESM.

I tried for a few minutes reading through the SWC docs and checking out the files in the node_modules/next/dist/build/next-config-ts/ folder:

  1. node_modules/next/dist/build/next-config-ts/transpile-config.js
  2. node_modules/next/dist/build/next-config-ts/require-hook.js

But my first attempts failed so far... not familiar with common SWC patterns for this.

Maybe upgrading to Node.js v22 for --experimental-require-module would help with being able to require ESM modules... 🤔

karlhorky avatar Sep 18 '24 12:09 karlhorky

Workaround

Edit: No longer needed for @shiki/rehype as of @shikijs/[email protected]: https://github.com/vercel/next.js/pull/68365#issuecomment-2598544304

For my use case, it seems like the ERR_PACKAGE_PATH_NOT_EXPORTED / No "exports" main defined error is no longer thrown with this patch (switching swc module.type to 'es6' and switching from require() to dynamic import()):

node_modules/next/dist/build/next-config-ts/transpile-config.js

diff --git a/node_modules/next/dist/build/next-config-ts/transpile-config.js b/node_modules/next/dist/build/next-config-ts/transpile-config.js
index f61819c..3f87f9b 100644
--- a/node_modules/next/dist/build/next-config-ts/transpile-config.js
+++ b/node_modules/next/dist/build/next-config-ts/transpile-config.js
@@ -24,7 +24,7 @@ function resolveSWCOptions(cwd, compilerOptions) {
             baseUrl: resolvedBaseUrl
         },
         module: {
-            type: 'commonjs'
+            type: 'es6'
         },
         isModule: 'unknown'
     };
@@ -59,8 +59,12 @@ async function transpileConfig({ nextConfigPath, cwd }) {
             (0, _requirehook.registerHook)(swcOptions);
             hasRequire = true;
         }
-        // filename & extension don't matter here
-        return (0, _requirehook.requireFromString)(code, (0, _nodepath.join)(cwd, 'next.config.compiled.js'));
+        // Support ESM in next.config.ts
+        // https://github.com/vercel/next.js/pull/68365#issuecomment-2358349887
+        const compiledConfigPath = (0, _nodepath.join)(cwd, '.next', 'next.config.compiled.mjs');
+        await (0, _promises.mkdir)((0, _nodepath.join)(cwd, '.next'), { recursive: true });
+        await (0, _promises.writeFile)(compiledConfigPath, code, 'utf8');
+        return await import(compiledConfigPath);
     } catch (error) {
         throw error;
     } finally{

Downside: Creates a new file in the .next/ folder

If you want to apply this patch, check out pnpm patch or patch-package

karlhorky avatar Sep 18 '24 12:09 karlhorky

@karlhorky Hi, thank you for sharing your case! I'm currently investigating on it, and will bring what's the best for you and the community's cases! Again, thank you for your suggestion, and patience.

devjiwonchoi avatar Sep 18 '24 14:09 devjiwonchoi

Notifying the following users due to files changed in this PR based on this repo's notify modifiers:

@timneutkens, @ijjk, @shuding, @huozhi:

packages/next/src/server/config.ts

vercel[bot] avatar Nov 19 '24 20:11 vercel[bot]

Do we remove the loader after the config is loaded?

No; Node.js doesn't have a deregister function yet.

x-ref: https://github.com/orgs/nodejs/discussions/55624#discussioncomment-11260337

Does it only apply to files relevant to the config or does it impact the load performance of unrelated files as well?

It does affect the unrelated files so far. Will inform in the docs, and will dig further on deregister and strip types.

devjiwonchoi avatar Nov 22 '24 16:11 devjiwonchoi

TODO:

  • remove extension overriding
  • update good docs

devjiwonchoi avatar Dec 12 '24 13:12 devjiwonchoi

2¢: Might be worth adding tests for import.meta.filename / import.meta.dirname. I encountered this today in next.config.ts:

/path/to/monorepo/apps/frontend/next.config.compiled.js:218
    outputFileTracingRoot: _nodepath.default.resolve(import.meta.dirname, '../..'),
                                                            ^^^^

SyntaxError: Cannot use 'import.meta' outside a module
    at wrapSafe (node:internal/modules/cjs/loader:1378:20)
    at Module._compile (node:internal/modules/cjs/loader:1428:41)
    at requireFromString (/path/to/monorepo/node_modules/next/dist/build/next-config-ts/require-hook.js:81:7)
    at transpileConfig (/path/to/monorepo/node_modules/next/dist/build/next-config-ts/transpile-config.js:63:51)
    at async loadConfig (/path/to/monorepo/node_modules/next/dist/server/config.js:771:36)
    at async Module.nextDev (/path/to/monorepo/node_modules/next/dist/cli/next-dev.js:190:14)

Node.js v20.18.1

This works as a temp solution:

const nextConfig: NextConfig = {
  outputFileTracingRoot: fileURLToPath(new URL('../..', import.meta.url)),
  // TODO (Alexander Kachkaev) [2024-12-20]: Replace ↑ with ↓ when https://github.com/vercel/next.js/pull/68365 is released
  // outputFileTracingRoot: path.resolve(import.meta.dirname, '../..'),
  
  /* ... */
};

export default nextConfig;

kachkaev avatar Dec 20 '24 00:12 kachkaev

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /home/runner/work/courses/courses/node_modules/@shikijs/vscode-textmate/package.json

@karlhorky for vscode-textmate the problem got fixed in the https://github.com/shikijs/vscode-textmate/pull/2, it fixes importing rehype-pretty-code and @shiki/rehype import in next.config.ts files

chrisweb avatar Jan 17 '25 14:01 chrisweb

@chrisweb thanks for the tip!

I can confirm that with @shikijs/[email protected] (looks like it was first released in @shikijs/[email protected]), my workaround to patch Next.js is no longer needed to import @shikijs/rehype in next.config.ts 🎉

karlhorky avatar Jan 17 '25 14:01 karlhorky

@devjiwonchoi are you still working on this?

stefanprobst avatar Aug 03 '25 12:08 stefanprobst

Looks like there is a new attempt to resolve this problem: https://github.com/vercel/next.js/pull/83120 👀

kachkaev avatar Aug 28 '25 14:08 kachkaev

Superseded by https://github.com/vercel/next.js/pull/83120

devjiwonchoi avatar Aug 29 '25 15:08 devjiwonchoi