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

Imports inside .css.ts files produce an error (Next Js) #1043

Open
toyi opened this issue Mar 15, 2023 · 26 comments
Open

Imports inside .css.ts files produce an error (Next Js) #1043

toyi opened this issue Mar 15, 2023 · 26 comments
Labels
nextjs Issue related to NextJS

Comments

@toyi
Copy link

toyi commented Mar 15, 2023

Describe the bug

At least on Next 13, some imports inside .css.ts files produce the following error:

NonErrorEmittedError: (Emitted value instead of an instance of Error) ReferenceError: $RefreshReg$ is not defined

This is triggered when the file containing the thing you import IS or EXPORTS a .tsx file that exports a function which has a name in PascalCase.

Codesandbox instructions: go to the styles/test.css.ts file and comment / uncomment the imports in order.
Some examples available in the codesandbox:

// problem.tsx

export const PascalCaseFunction = () => {
  console.log(":/");
};
// test.css.ts

import { PascalCaseFunction } from "./problem"

PascalCaseFunction() // error

// works.tsx

export const camelCaseFunction = () => {
  console.log("WORKS");
};
// test.css.ts

import { camelCaseFunction } from "./works"

camelCaseFunction () // works

// multiple_exports.tsx

export * from "./problem";
export * from "./works";
// test.css.ts

import { camelCaseFunction } from "./multiple_exports"

camelCaseFunction () // error (because multiple_exports also exports the PascalCaseFunction)

Not lying, I had a pretty hard testing / debugging time on this one, that's not obvious at all :p

Reproduction

https://codesandbox.io/p/sandbox/agitated-ride-g44g7r

System Info

System:
    OS: Linux 5.15 Ubuntu 22.04.1 LTS 22.04.1 LTS (Jammy Jellyfish)
    CPU: (8) x64 12th Gen Intel(R) Core(TM) i7-12700K
    Memory: 8.07 GB / 15.62 GB
    Container: Yes
    Shell: 5.1.16 - /bin/bash
  Binaries:
    Node: 16.19.1 - /usr/local/bin/node
    Yarn: 3.3.1 - /usr/local/bin/yarn
    npm: 8.19.3 - /usr/local/bin/npm

Used Package Manager

npm

Logs

(in the terminal of course)


NonErrorEmittedError: (Emitted value instead of an instance of Error) ReferenceError: $RefreshReg$ is not defined
Import trace for requested module:
./styles/test.css.ts


### Validations

- [X] Check that there isn't [already an issue](https://github.com/vanilla-extract-css/vanilla-extract/issues) that reports the same bug to avoid creating a duplicate.
- [X] The provided reproduction is a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of the bug.
@mrm007
Copy link
Contributor

mrm007 commented Mar 16, 2023

This seems like an issue with React Fast Refresh, specifically the Webpack plugin which Next.js uses: https://github.com/vercel/next.js/blob/canary/packages/react-refresh-utils/ReactRefreshWebpackPlugin.ts

There's no documentation for that plugin as far as I'm aware, but we can look at another popular Webpack plugin to figure out what's going on: https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/docs/TROUBLESHOOTING.md#usage-with-indirection-like-workers-and-js-templates

So it looks like what's happening here is your .css.ts files imports [something that Babel thinks is] a React component and the instrumented code doesn't find the $RefreshReg$ function it expected to be there. (More details about Fast Refresh here)

TL;DR: It's better to have your .css.ts files be leaf nodes in your dependency tree i.e. import from not into styles/test.css.ts. If you need to import constants or simple values into your .css.ts files, make sure they're imported from leaf nodes as well.

@toyi
Copy link
Author

toyi commented Mar 16, 2023

Thank you for your quick answer!

In my specific case, the file I was trying to import contained a simple object with string values, but was exported from a barrel file alongside other things, some of those were React components.

They (the React components) were not imported into the .css.ts file, but by just being exported from the same file as my import was causing the error. I know, there is a lot of "import / export" in these sentences, it can be confusing (case 3 from my issue, the multiple_exports.ts).

Anyway, I splitted this barrel file in two, components / non-components, and now every thing works fine :)

Maybe this kind of issues should be documented somewhere? The first time you encounter this error, you don't really know where to look at, especially because you don't directly import the things that cause problems (the React components).

@peterfoeng
Copy link

Hi @toyi do you have a sample repo to take a look, trying to solve similar issue

@toyi
Copy link
Author

toyi commented Apr 5, 2023

Unfortunately I don't have a sample repo available, I just have the codesandbox provided in the issue, but that should do it.

The solution (or should I say "workaround") was to ensure the file you are importing into the .css.ts comes from a file that doesn't export anything that IS or MIGHT BE MISTAKEN FOR a React component.

Take a look at the sandbox, you have multiple examples of working / not working cases.

The main idea is to not import anything that (is a function|is exported alongside other elements that are functions) starting with a capital letter.

@ssijak
Copy link

ssijak commented Jun 7, 2023

@toyi Thanks a lot, I think your investigation saved me from a ton of lost time doing it myself. I have the exact same scenario with Next13.
Monorepo where one package is "ui" library implemented with vanilla extract and all of the react components and helper functions are exported via one index file.
Then in my .css.ts file in Next13 app inside the monorepo I was importing a helper function (which is just a normal function sitting in a .ts file in ui lib) like import {helperFunctionName} from 'ui' and I was getting this weird error.
Changing the import to the exact path like import {helperFunctionName} from 'ui/styles/helperFunctionFile' fixed the error -_-

@shelooks16
Copy link

This error also occurred to me in a monorepo. I was using barrel files to combine exports for multiple .css.ts files.

// theme/index.ts
export * from './contract.css';
export * from './sprinkles.css';

// then
import { sprinkles, theme } from 'theme'

Importing directly from .css.ts helped

// before, error pops up
import { sprinkles, theme } from 'theme';

// after, no error
import { sprinkles } from 'theme/sprinkles.css';
import { theme } from 'theme/contract.css';

@V-iktor
Copy link

V-iktor commented Aug 22, 2023

Importing directly from .css.ts helped

@shelooks16 thanks for that, works like a charm

@enyelsequeira
Copy link

Hello any feedback on this yet or can anyone help with this, I am facing this issue and tried some solutions here, but nothing this is how my files look
image

@askoufis
Copy link
Contributor

askoufis commented Sep 25, 2023

Hello any feedback on this yet or can anyone help with this

Is anything other than vars being exported from that theme file?

@enyelsequeira
Copy link

Hello any feedback on this yet or can anyone help with this

Is anything other than vars being exported from that theme file?

Hey So all it export is something like this
image

@askoufis
Copy link
Contributor

askoufis commented Sep 25, 2023

Hello any feedback on this yet or can anyone help with this

Is anything other than vars being exported from that theme file?

Hey So all it export is something like this
image

Hmm ok. I wonder if the issue is @mantine/core? It's exporting components and utilities. What happens if you remove the rem import from Welcome.css.ts file?

@enyelsequeira
Copy link

Hello any feedback on this yet or can anyone help with this

Is anything other than vars being exported from that theme file?

Hey So all it export is something like this
image

Hmm ok. I wonder if the issue is @mantine/core? It's exporting components and utilities. What happens if you remove the rem import from Welcome.css.ts file?

Still the same issue I have a demo repo here link . the odd part is I am using next13 with the pages dir and this happens however if I use the app dir it works fine

@enyelsequeira
Copy link

So has there been anything done about this? it seems to still be on triage?

@guillaumewuip
Copy link

guillaumewuip commented Oct 4, 2023

I'm reporting the issue also on a monorepo. __webpack_require__.$Refresh$.register is called on exports of tslib. I've extracted part of what @vanilla-extract/integration is passing to eval:

var _c, _c2, _c3, _c4, _c5, _c6, _c7;
__webpack_require__.$Refresh$.register(_c, "O");
__webpack_require__.$Refresh$.register(_c2, "P");
__webpack_require__.$Refresh$.register(_c3, "E");
__webpack_require__.$Refresh$.register(_c4, "T");
__webpack_require__.$Refresh$.register(_c5, "I");
__webpack_require__.$Refresh$.register(_c6, "D");
__webpack_require__.$Refresh$.register(_c7, "A");
full virtual/_tslib.js part
/***/ "../my-lib/dist/esm/_virtual/_tslib.js":
/*!*********************************************!*\
  !*** ../my-lib/dist/esm/_virtual/_tslib.js ***!
  \*********************************************/
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   __addDisposableResource: function() { return /* binding */ D; },
/* harmony export */   __assign: function() { return /* binding */ r; },
/* harmony export */   __asyncDelegator: function() { return /* binding */ O; },
/* harmony export */   __asyncGenerator: function() { return /* binding */ g; },
/* harmony export */   __asyncValues: function() { return /* binding */ j; },
/* harmony export */   __await: function() { return /* binding */ m; },
/* harmony export */   __awaiter: function() { return /* binding */ s; },
/* harmony export */   __classPrivateFieldGet: function() { return /* binding */ T; },
/* harmony export */   __classPrivateFieldIn: function() { return /* binding */ I; },
/* harmony export */   __classPrivateFieldSet: function() { return /* binding */ k; },
/* harmony export */   __createBinding: function() { return /* binding */ y; },
/* harmony export */   __decorate: function() { return /* binding */ o; },
/* harmony export */   __disposeResources: function() { return /* binding */ A; },
/* harmony export */   __esDecorate: function() { return /* binding */ i; },
/* harmony export */   __exportStar: function() { return /* binding */ d; },
/* harmony export */   __extends: function() { return /* binding */ t; },
/* harmony export */   __generator: function() { return /* binding */ p; },
/* harmony export */   __importDefault: function() { return /* binding */ x; },
/* harmony export */   __importStar: function() { return /* binding */ E; },
/* harmony export */   __makeTemplateObject: function() { return /* binding */ P; },
/* harmony export */   __metadata: function() { return /* binding */ l; },
/* harmony export */   __param: function() { return /* binding */ a; },
/* harmony export */   __propKey: function() { return /* binding */ u; },
/* harmony export */   __read: function() { return /* binding */ b; },
/* harmony export */   __rest: function() { return /* binding */ n; },
/* harmony export */   __runInitializers: function() { return /* binding */ c; },
/* harmony export */   __setFunctionName: function() { return /* binding */ f; },
/* harmony export */   __spread: function() { return /* binding */ v; },
/* harmony export */   __spreadArray: function() { return /* binding */ _; },
/* harmony export */   __spreadArrays: function() { return /* binding */ w; },
/* harmony export */   __values: function() { return /* binding */ h; },
/* harmony export */   "default": function() { return /* binding */ C; }
/* harmony export */ });
var e = function (t, r) {
  return e = Object.setPrototypeOf || {
    __proto__: []
  } instanceof Array && function (e, t) {
    e.__proto__ = t;
  } || function (e, t) {
    for (var r in t) Object.prototype.hasOwnProperty.call(t, r) && (e[r] = t[r]);
  }, e(t, r);
};
function t(t, r) {
  if ("function" != typeof r && null !== r) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
  function n() {
    this.constructor = t;
  }
  e(t, r), t.prototype = null === r ? Object.create(r) : (n.prototype = r.prototype, new n());
}
var r = function () {
  return r = Object.assign || function (e) {
    for (var t, r = 1, n = arguments.length; r < n; r++) for (var o in t = arguments[r]) Object.prototype.hasOwnProperty.call(t, o) && (e[o] = t[o]);
    return e;
  }, r.apply(this, arguments);
};
function n(e, t) {
  var r = {};
  for (var n in e) Object.prototype.hasOwnProperty.call(e, n) && t.indexOf(n) < 0 && (r[n] = e[n]);
  if (null != e && "function" == typeof Object.getOwnPropertySymbols) {
    var o = 0;
    for (n = Object.getOwnPropertySymbols(e); o < n.length; o++) t.indexOf(n[o]) < 0 && Object.prototype.propertyIsEnumerable.call(e, n[o]) && (r[n[o]] = e[n[o]]);
  }
  return r;
}
function o(e, t, r, n) {
  var o,
    a = arguments.length,
    i = a < 3 ? t : null === n ? n = Object.getOwnPropertyDescriptor(t, r) : n;
  if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) i = Reflect.decorate(e, t, r, n);else for (var c = e.length - 1; c >= 0; c--) (o = e[c]) && (i = (a < 3 ? o(i) : a > 3 ? o(t, r, i) : o(t, r)) || i);
  return a > 3 && i && Object.defineProperty(t, r, i), i;
}
function a(e, t) {
  return function (r, n) {
    t(r, n, e);
  };
}
function i(e, t, r, n, o, a) {
  function i(e) {
    if (void 0 !== e && "function" != typeof e) throw new TypeError("Function expected");
    return e;
  }
  for (var c, u = n.kind, f = "getter" === u ? "get" : "setter" === u ? "set" : "value", l = !t && e ? n.static ? e : e.prototype : null, s = t || (l ? Object.getOwnPropertyDescriptor(l, n.name) : {}), p = !1, y = r.length - 1; y >= 0; y--) {
    var d = {};
    for (var h in n) d[h] = "access" === h ? {} : n[h];
    for (var h in n.access) d.access[h] = n.access[h];
    d.addInitializer = function (e) {
      if (p) throw new TypeError("Cannot add initializers after decoration has completed");
      a.push(i(e || null));
    };
    var b = (0, r[y])("accessor" === u ? {
      get: s.get,
      set: s.set
    } : s[f], d);
    if ("accessor" === u) {
      if (void 0 === b) continue;
      if (null === b || "object" != typeof b) throw new TypeError("Object expected");
      (c = i(b.get)) && (s.get = c), (c = i(b.set)) && (s.set = c), (c = i(b.init)) && o.unshift(c);
    } else (c = i(b)) && ("field" === u ? o.unshift(c) : s[f] = c);
  }
  l && Object.defineProperty(l, n.name, s), p = !0;
}
function c(e, t, r) {
  for (var n = arguments.length > 2, o = 0; o < t.length; o++) r = n ? t[o].call(e, r) : t[o].call(e);
  return n ? r : void 0;
}
function u(e) {
  return "symbol" == typeof e ? e : "".concat(e);
}
function f(e, t, r) {
  return "symbol" == typeof t && (t = t.description ? "[".concat(t.description, "]") : ""), Object.defineProperty(e, "name", {
    configurable: !0,
    value: r ? "".concat(r, " ", t) : t
  });
}
function l(e, t) {
  if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(e, t);
}
function s(e, t, r, n) {
  return new (r || (r = Promise))(function (o, a) {
    function i(e) {
      try {
        u(n.next(e));
      } catch (e) {
        a(e);
      }
    }
    function c(e) {
      try {
        u(n.throw(e));
      } catch (e) {
        a(e);
      }
    }
    function u(e) {
      var t;
      e.done ? o(e.value) : (t = e.value, t instanceof r ? t : new r(function (e) {
        e(t);
      })).then(i, c);
    }
    u((n = n.apply(e, t || [])).next());
  });
}
function p(e, t) {
  var r,
    n,
    o,
    a,
    i = {
      label: 0,
      sent: function () {
        if (1 & o[0]) throw o[1];
        return o[1];
      },
      trys: [],
      ops: []
    };
  return a = {
    next: c(0),
    throw: c(1),
    return: c(2)
  }, "function" == typeof Symbol && (a[Symbol.iterator] = function () {
    return this;
  }), a;
  function c(c) {
    return function (u) {
      return function (c) {
        if (r) throw new TypeError("Generator is already executing.");
        for (; a && (a = 0, c[0] && (i = 0)), i;) try {
          if (r = 1, n && (o = 2 & c[0] ? n.return : c[0] ? n.throw || ((o = n.return) && o.call(n), 0) : n.next) && !(o = o.call(n, c[1])).done) return o;
          switch (n = 0, o && (c = [2 & c[0], o.value]), c[0]) {
            case 0:
            case 1:
              o = c;
              break;
            case 4:
              return i.label++, {
                value: c[1],
                done: !1
              };
            case 5:
              i.label++, n = c[1], c = [0];
              continue;
            case 7:
              c = i.ops.pop(), i.trys.pop();
              continue;
            default:
              if (!(o = i.trys, (o = o.length > 0 && o[o.length - 1]) || 6 !== c[0] && 2 !== c[0])) {
                i = 0;
                continue;
              }
              if (3 === c[0] && (!o || c[1] > o[0] && c[1] < o[3])) {
                i.label = c[1];
                break;
              }
              if (6 === c[0] && i.label < o[1]) {
                i.label = o[1], o = c;
                break;
              }
              if (o && i.label < o[2]) {
                i.label = o[2], i.ops.push(c);
                break;
              }
              o[2] && i.ops.pop(), i.trys.pop();
              continue;
          }
          c = t.call(e, i);
        } catch (e) {
          c = [6, e], n = 0;
        } finally {
          r = o = 0;
        }
        if (5 & c[0]) throw c[1];
        return {
          value: c[0] ? c[1] : void 0,
          done: !0
        };
      }([c, u]);
    };
  }
}
var y = Object.create ? function (e, t, r, n) {
  void 0 === n && (n = r);
  var o = Object.getOwnPropertyDescriptor(t, r);
  o && !("get" in o ? !t.__esModule : o.writable || o.configurable) || (o = {
    enumerable: !0,
    get: function () {
      return t[r];
    }
  }), Object.defineProperty(e, n, o);
} : function (e, t, r, n) {
  void 0 === n && (n = r), e[n] = t[r];
};
function d(e, t) {
  for (var r in e) "default" === r || Object.prototype.hasOwnProperty.call(t, r) || y(t, e, r);
}
function h(e) {
  var t = "function" == typeof Symbol && Symbol.iterator,
    r = t && e[t],
    n = 0;
  if (r) return r.call(e);
  if (e && "number" == typeof e.length) return {
    next: function () {
      return e && n >= e.length && (e = void 0), {
        value: e && e[n++],
        done: !e
      };
    }
  };
  throw new TypeError(t ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function b(e, t) {
  var r = "function" == typeof Symbol && e[Symbol.iterator];
  if (!r) return e;
  var n,
    o,
    a = r.call(e),
    i = [];
  try {
    for (; (void 0 === t || t-- > 0) && !(n = a.next()).done;) i.push(n.value);
  } catch (e) {
    o = {
      error: e
    };
  } finally {
    try {
      n && !n.done && (r = a.return) && r.call(a);
    } finally {
      if (o) throw o.error;
    }
  }
  return i;
}
function v() {
  for (var e = [], t = 0; t < arguments.length; t++) e = e.concat(b(arguments[t]));
  return e;
}
function w() {
  for (var e = 0, t = 0, r = arguments.length; t < r; t++) e += arguments[t].length;
  var n = Array(e),
    o = 0;
  for (t = 0; t < r; t++) for (var a = arguments[t], i = 0, c = a.length; i < c; i++, o++) n[o] = a[i];
  return n;
}
function _(e, t, r) {
  if (r || 2 === arguments.length) for (var n, o = 0, a = t.length; o < a; o++) !n && o in t || (n || (n = Array.prototype.slice.call(t, 0, o)), n[o] = t[o]);
  return e.concat(n || Array.prototype.slice.call(t));
}
function m(e) {
  return this instanceof m ? (this.v = e, this) : new m(e);
}
function g(e, t, r) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var n,
    o = r.apply(e, t || []),
    a = [];
  return n = {}, i("next"), i("throw"), i("return"), n[Symbol.asyncIterator] = function () {
    return this;
  }, n;
  function i(e) {
    o[e] && (n[e] = function (t) {
      return new Promise(function (r, n) {
        a.push([e, t, r, n]) > 1 || c(e, t);
      });
    });
  }
  function c(e, t) {
    try {
      (r = o[e](t)).value instanceof m ? Promise.resolve(r.value.v).then(u, f) : l(a[0][2], r);
    } catch (e) {
      l(a[0][3], e);
    }
    var r;
  }
  function u(e) {
    c("next", e);
  }
  function f(e) {
    c("throw", e);
  }
  function l(e, t) {
    e(t), a.shift(), a.length && c(a[0][0], a[0][1]);
  }
}
function O(e) {
  var t, r;
  return t = {}, n("next"), n("throw", function (e) {
    throw e;
  }), n("return"), t[Symbol.iterator] = function () {
    return this;
  }, t;
  function n(n, o) {
    t[n] = e[n] ? function (t) {
      return (r = !r) ? {
        value: m(e[n](t)),
        done: !1
      } : o ? o(t) : t;
    } : o;
  }
}
_c = O;
function j(e) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var t,
    r = e[Symbol.asyncIterator];
  return r ? r.call(e) : (e = h(e), t = {}, n("next"), n("throw"), n("return"), t[Symbol.asyncIterator] = function () {
    return this;
  }, t);
  function n(r) {
    t[r] = e[r] && function (t) {
      return new Promise(function (n, o) {
        (function (e, t, r, n) {
          Promise.resolve(n).then(function (t) {
            e({
              value: t,
              done: r
            });
          }, t);
        })(n, o, (t = e[r](t)).done, t.value);
      });
    };
  }
}
function P(e, t) {
  return Object.defineProperty ? Object.defineProperty(e, "raw", {
    value: t
  }) : e.raw = t, e;
}
_c2 = P;
var S = Object.create ? function (e, t) {
  Object.defineProperty(e, "default", {
    enumerable: !0,
    value: t
  });
} : function (e, t) {
  e.default = t;
};
function E(e) {
  if (e && e.__esModule) return e;
  var t = {};
  if (null != e) for (var r in e) "default" !== r && Object.prototype.hasOwnProperty.call(e, r) && y(t, e, r);
  return S(t, e), t;
}
_c3 = E;
function x(e) {
  return e && e.__esModule ? e : {
    default: e
  };
}
function T(e, t, r, n) {
  if ("a" === r && !n) throw new TypeError("Private accessor was defined without a getter");
  if ("function" == typeof t ? e !== t || !n : !t.has(e)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return "m" === r ? n : "a" === r ? n.call(e) : n ? n.value : t.get(e);
}
_c4 = T;
function k(e, t, r, n, o) {
  if ("m" === n) throw new TypeError("Private method is not writable");
  if ("a" === n && !o) throw new TypeError("Private accessor was defined without a setter");
  if ("function" == typeof t ? e !== t || !o : !t.has(e)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return "a" === n ? o.call(e, r) : o ? o.value = r : t.set(e, r), r;
}
function I(e, t) {
  if (null === t || "object" != typeof t && "function" != typeof t) throw new TypeError("Cannot use 'in' operator on non-object");
  return "function" == typeof e ? t === e : e.has(t);
}
_c5 = I;
function D(e, t, r) {
  if (null != t) {
    if ("object" != typeof t && "function" != typeof t) throw new TypeError("Object expected.");
    var n;
    if (r) {
      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
      n = t[Symbol.asyncDispose];
    }
    if (void 0 === n) {
      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
      n = t[Symbol.dispose];
    }
    if ("function" != typeof n) throw new TypeError("Object not disposable.");
    e.stack.push({
      value: t,
      dispose: n,
      async: r
    });
  } else r && e.stack.push({
    async: !0
  });
  return t;
}
_c6 = D;
var R = "function" == typeof SuppressedError ? SuppressedError : function (e, t, r) {
  var n = new Error(r);
  return n.name = "SuppressedError", n.error = e, n.suppressed = t, n;
};
function A(e) {
  function t(t) {
    e.error = e.hasError ? new R(t, e.error, "An error was suppressed during disposal.") : t, e.hasError = !0;
  }
  return function r() {
    for (; e.stack.length;) {
      var n = e.stack.pop();
      try {
        var o = n.dispose && n.dispose.call(n.value);
        if (n.async) return Promise.resolve(o).then(r, function (e) {
          return t(e), r();
        });
      } catch (e) {
        t(e);
      }
    }
    if (e.hasError) throw e.error;
  }();
}
_c7 = A;
var C = {
  __extends: t,
  __assign: r,
  __rest: n,
  __decorate: o,
  __param: a,
  __metadata: l,
  __awaiter: s,
  __generator: p,
  __createBinding: y,
  __exportStar: d,
  __values: h,
  __read: b,
  __spread: v,
  __spreadArrays: w,
  __spreadArray: _,
  __await: m,
  __asyncGenerator: g,
  __asyncDelegator: O,
  __asyncValues: j,
  __makeTemplateObject: P,
  __importStar: E,
  __importDefault: x,
  __classPrivateFieldGet: T,
  __classPrivateFieldSet: k,
  __classPrivateFieldIn: I,
  __addDisposableResource: D,
  __disposeResources: A
};

var _c, _c2, _c3, _c4, _c5, _c6, _c7;
__webpack_require__.$Refresh$.register(_c, "O");
__webpack_require__.$Refresh$.register(_c2, "P");
__webpack_require__.$Refresh$.register(_c3, "E");
__webpack_require__.$Refresh$.register(_c4, "T");
__webpack_require__.$Refresh$.register(_c5, "I");
__webpack_require__.$Refresh$.register(_c6, "D");
__webpack_require__.$Refresh$.register(_c7, "A");

/***/ }),

I'm blocked with the issue, as I can't play with leaf nodes / filenames / exports / to bypass that. Any idea?

@guillaumewuip
Copy link

guillaumewuip commented Oct 7, 2023

I've come up with patching @vanilla-extract/integration to mitigate the $Refresh$ issue by removing the problematic lines from source

diff --git a/dist/vanilla-extract-integration.cjs.dev.js b/dist/vanilla-extract-integration.cjs.dev.js
index f9ece42d38952835bb6c9e3414f64807d9a3d79c..07e3d34ddb0457c057d154c7b31047f40fd119b7 100644
--- a/dist/vanilla-extract-integration.cjs.dev.js
+++ b/dist/vanilla-extract-integration.cjs.dev.js
@@ -128,7 +128,7 @@ async function processVanillaFile({
   const adapterBoundSource = `
     require('@vanilla-extract/css/adapter').setAdapter(__adapter__);
     ${source}
-  `;
+  `.replaceAll(/.*__webpack_require__\.\$Refresh\$.*/g, '');
   const evalResult = evalCode__default["default"](adapterBoundSource, filePath, {
     console,
     process,

@askoufis
Copy link
Contributor

askoufis commented Oct 15, 2023

Looking at your demo repo, I think it could be an issue with how mantine exports a combination of components and non-components from @mantine/core, as mentioned before. This can cause issues with react refesh, as evidenced in #1072.

It is strange that this only occurs with the pages dir and not app dir.

@qmahmoudi74
Copy link

any solution yet?

@askoufis
Copy link
Contributor

askoufis commented Nov 9, 2023

any solution yet?

@qmahmoudi74

Depends what your issue is. Have you tried separating your React component exports from your style/theme exports?

@askoufis askoufis added nextjs Issue related to NextJS and removed nextjs labels Nov 16, 2023
@mbrookson
Copy link

I've just spent hours upgrading a repo from v6 to v7 replacing createStyles with vanilla extract and now come across this issue. Next.js 13 pages dir app. Followed the Mantine upgrade docs + vanilla extract docs. No idea how to resolve it.

./src/components/layouts/Footer.css.ts
NonErrorEmittedError: (Emitted value instead of an instance of Error) ReferenceError: document is not defined

@mbrookson
Copy link

Upgrading to Next.js 14 also didn't help with this issue.

In the end I've switched use CSS modules as recommended for now. However, would be great to understand if this issue could be resolved as I prefer CSS-in-JS styles with TypeScript and this migration to CSS has involved a LOT of work 😅

@6mint
Copy link

6mint commented Apr 23, 2024

Upgrading to Next.js 14.2 triggered this problem for me (see issue#1393). My guess would be that these issues are related and would be curious if this fix works.
The outcome should be the same as the solution @guillaumewuip proposed but without patching.

@tadhglewis
Copy link

tadhglewis commented Jun 27, 2024

👋 I ran into I think a related issue to this thread when using Mantine + Vanilla Extract + NextJS.

I was getting the following error
Screenshot 2024-06-28 at 12 57 19 AM

The guide on https://mantine.dev/styles/vanilla-extract/#theming says to create a theme.css.ts file with the following contents:

// theme.css.ts
import { createTheme } from '@mantine/core';
import { themeToVars } from '@mantine/vanilla-extract';

// Do not forget to pass theme to MantineProvider
export const theme = createTheme({
  fontFamily: 'serif',
  primaryColor: 'cyan',
});

// CSS variables object, can be access in *.css.ts files
export const vars = themeToVars(theme);

This for some reasons bricks the compiling. I fixed this by creating a separate vars.css.ts file with the following contents and removing themeToVars part from theme.css.ts

import { themeToVars } from "@mantine/vanilla-extract";
import { theme } from "./theme.css";

export const vars = themeToVars(theme);

Hopefully this helps some peopel

@yulolimum
Copy link

Thank you @tadhglewis for the pointer. My issue was that I'm using Mantine's Textarea.extend in the same file where themeToVars is called. Textarea uses react-textarea-autosize which requires document. The conflict is happening somewhere in the client vs server nextjs mess and it's difficult to debug. The theme is consumed on the server (in layout), but "vars" are consumed intermixed. Moving the extend() functionality out of the file and not including the components: {} object in the call fixed the issue.

Related issues:
mantinedev/mantine#6719
Andarist/react-textarea-autosize#335

@MJSPollard
Copy link

Not a single solution worked for me even for the simplest theme with nothing else in the file. Spent hours trying everything but was never able to use the vars in a .css.ts file using themeToVars with mantine 7.12.1 and nextjs 14.0.4. In the end I ended up copy and pasting the theme values into a new object so I could use them and that worked but :(

@6mint
Copy link

6mint commented Sep 21, 2024

Is this your error?
NonErrorEmittedError: (Emitted value instead of an instance of Error) ReferenceError: $RefreshReg$ is not defined

If so you can try:

next.config.js

const { createVanillaExtractPlugin } = require("@vanilla-extract/next-plugin");

const withVanillaExtract = createVanillaExtractPlugin();

/** @type {import('next').NextConfig} */
let nextConfig = {
    webpack(config, { nextRuntime, webpack }) {
        if (!nextRuntime) {
            config.plugins.push(
                new webpack.BannerPlugin({
                    banner: `$RefreshReg$ = () => {};\n$RefreshSig$ = () => () => {};\n`,
                    raw: true,
                    entryOnly: true,
                    include: /\.css.ts$/,
                }),
            );
        }
        return config;
    },
};

nextConfig = withVanillaExtract(nextConfig);

module.exports = nextConfig;

@tobysmith568
Copy link

For those getting NonErrorEmittedError: (Emitted value instead of an instance of Error) ReferenceError: document is not defined when using the pages directory of a Next.JS app with mantine & vanilla-extract: I have found that merely adding the Next.JS "app directory" to my project fixes the issue. This seems to work even if you're using output: "standalone" in your next.config.js.

mkdir -p ./src/app
touch ./src/app/.gitkeep

At this point I don't know if the issue lies within Mantine, Vanilla Extract, or even Next.JS itself, but hopefully this can help unstick some people...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
nextjs Issue related to NextJS
Projects
None yet
Development

No branches or pull requests