payload: Error interpreting SCSS file: @import '../../../scss/styles';

Link to reproduction

test:int _community

To Reproduce

I installed Payload CMS via the recommended method (npx create-payload-app ) with Node 18.15.0, set up MongoDB, used the blog option for the base installation with full Typescript and ScSS support. I successfully added a number of collections and field hooks. All good. Then add a custom component as detailed in your documentation:

 admin: {
    defaultColumns: [
      "displayName",
      "user",
      "edition",
      "themes",
      "published",
      "updatedAt",
    ],
    useAsTitle: "displayName",
    components: {
      views: {
        List: SubmissionList,
      },
    },
  },

So far I only have a bare bones component (again based on your documentation):

import React from "react";
import { List, type Props } from "payload/components/views/List";

export const SubmissionList: React.FC<Props> = (props) => (
  <div className="submission-list">
    <p>
      Some text before the default list view component. If you just want to do
      that, you can also use the admin.components.list.BeforeList hook
    </p>
    <List {...props} />
  </div>
);

Describe the Bug

On enabling any custom collection component, I get this error message when running yarn dev. The project builds correctly, but fails on yarn serve:

`/Users/neil/Sites/platform3/rca/payload/plrca/node_modules/payload/dist/admin/components/icons/Chevron/index.scss:1
@import '../../../scss/styles';
^

SyntaxError: Invalid or unexpected token
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1176:20)
    at Module._compile (node:internal/modules/cjs/loader:1218:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Object.require.extensions.<computed> [as .js] (/Users/xxxx/Sites/platform3/rca/payload/plrca/node_modules/ts-node/src/index.ts:1045:43)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Function.Module._load (node:internal/modules/cjs/loader:958:12)
    at Module.require (node:internal/modules/cjs/loader:1141:19)
    at require (node:internal/modules/cjs/helpers:110:18)
    at Object.<anonymous> (/Users/xxxx/Sites/platform3/rca/payload/plrca/node_modules/payload/src/admin/components/icons/Chevron/index.tsx:3:1)`

Am I missing something? Did I skip a configuration step? It seems to be interpreting the file as typescript. I checked sass and sass-loader have been correctly installed. Thanks in advance

Payload Version

1.11.8

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 5
  • Comments: 49 (25 by maintainers)

Commits related to this issue

Most upvoted comments

Here is a repro: https://github.com/thgh/payload-3120

» yarn start    
yarn run v1.22.19
$ nest start
/.../payload-3120/node_modules/payload/dist/admin/components/elements/Banner/index.scss:1
@import '../../../scss/styles.scss';
^

SyntaxError: Invalid or unexpected token
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1153:20)

Is there an easy way to fix it ? thx

I can only give you a (dirty) work around. I imported the following code at the beginning of the server entry script (server.ts):

/**
 * This will fix an issue with react component loading on server side.
 * See: https://github.com/payloadcms/payload/issues/3120
 */

import intercept from 'intercept-require';

const cssPattern = /\.(s?css|svg|png|jpe?g|gif|ttf)$/i;

intercept(
    (module, info) => {
        if (info.didShortCircuit) {
            return {};
        }

        if (info.error) {
            throw info.error;
        }

        return module;
    },
    {
        shortCircuit: true,
        shortCircuitMatch: (info) => cssPattern.test(info.extname ?? ''),
    }
);

I am using intercept-require for this. This has no Typings, so you may have to add it manually when using typescript:

declare module "intercept-require" {
    export type InterceptFn = (module: unknown, info: RequireInfo) => unknown;
    export type RestoreFn = () => void;

    export interface RequireInfo {
        readonly moduleId: string;
        readonly callingFile: string;
        readonly native: boolean;
        readonly extname: string|null;
        readonly thirdParty: boolean;
        readonly absPath: string;
        readonly absPathResolvedCorrectly: boolean;
        readonly local: boolean;
        readonly error: Error|null;
        readonly attemptedShortCircuit?: boolean;
        readonly didShortCircuit?: boolean;
    }

    export interface InterceptShortCircuitOptions {
        shortCircuit: true;
        shortCircuitMatch?: (info: RequireInfo) => boolean;
    }

    export type InterceptOptions = InterceptShortCircuitOptions | {shortCircuit: false};

    export default function intercept(interceptor: InterceptFn, options?: InterceptOptions): RestoreFn;
}

Same thing here, was working for a while and when I continued to work on my project, I had the same exact error.

In another project we used transpilePackages: ["@payloadcms/plugin-form-builder"]. But this time payload cms is in standalone / api mod.

I tried this nodemon dev command: cross-env PAYLOAD_CONFIG_PATH=src/payload.config.ts nodemon -e ts,js --exec ts-node -r tsconfig-paths/register ./src/server.ts

With this custom webpack configuration:

  admin: {
    webpack: config => ({
        ...config,
        externals: [nodeExternals()],
        module: {
          ...config.module,
          rules: [
            ...config.module.rules,
            {
              test: /\.scss$/,
              exclude: /node_modules/,
              use: ['sass-loader'],
            },
          ],
        },
      }),
  },

Using webpack-node-externals and a default sass-loader to just try to dodge this error.

As tux-rampage said previously, it’s because of .tsx compilation on server side.

Why a core admin package is crashing issues ? The .scss file is located inside /node_modules/payload/dist/admin/components/forms/Label/index.scss:1. So it’s located in dist folder. Shouldn’t this file has been already transpiled to just CSS ?

Is there an easy way to fix it ? thx

Same issue here. Bare payload project without NextJS. Everything runs fine until I add any custom component to a field as described in the docs. As soon as I do this, the error appears.

Experiencing same problem, but im using astrojs framework, and decided to convert lexical json to html on “frontend”, but actually its on server at the time of html generating, copied the code from payload docs,

import type { SerializedEditorState } from 'lexical'
import {
  type SanitizedEditorConfig,
  convertLexicalToHTML,
  consolidateHTMLConverters,
} from '@payloadcms/richtext-lexical'

async function lexicalToHTML(editorData: SerializedEditorState, editorConfig: SanitizedEditorConfig) {
  return await convertLexicalToHTML({
    converters: consolidateHTMLConverters({ editorConfig }),
    data: editorData,
  })
} 

and getting such error:

/home/office/projects/20231120_domainRU_bani/node_modules/payload/dist/admin/components/elements/Banner/index.scss:1
@import '../../../scss/styles.scss';

For some reason @payload/richtext-lexical, imports payload with its admin part which has a lot of scss, but it does not make a lot of sense for me, why would we need any scss to convert json to html.

Hey everyone! While we would love to help you fix this issue, it is very hard to do so without an actual reproduction. We are going to close this for now, but if anyone wants to submit a link to a branch or fork that throws this error we will gladly re-open it.

If any of you are using next-payload packages or the next-custom-server template - ensure that you are adding use client to the top of any files that import .scss files inside the app folder.

Again, if anyone can link a reproduction we will take a look.

Thanks!

Gave it up and then it started working!

Resolved it like this: (note that most of these things relate to Nest.js)

  • Downgrade to Payload 1 to resolve the scss issue
  • Add process.env.PAYLOAD_CONFIG_PATH = __dirname.replace('dist', 'src') + '/payload.config.ts' before init
  • Disable the nest swc builder
  • Remove the dist folder (or run nest start --watch twice or something)

Following up on this. I had my custom components declared in the same file I was declaring my collection, and therefore a .tsx extension on my Collection.tsx file.

All of my other collections were in .ts files except for this one. I moved my custom component into its own .tsx file and imported it into my Collection.ts and this error went away.

Also had to add

"browser": {
    "fs": false
  },

to my package.json

Thx for the snippet, I hope I will not have to do this 😞

I think that 50% of my issues are because of things exported inside the payload package. For example, when I want to type things using types inside payload/dist/payload, I have a bad mix between things that should stay in the node ecosystem but are trying to be bundled to Payload Front admin (react part).

Additional errors are coming form the fact that tsconfig.json is not handled at 100% in standalone mod. Aliases break and we have to fix things using webpack inside payload.config.ts. And then after fixing things with webpack plugins, we have weird behaviors at the build time. We fix things one more time using other webpack configuration like resolve:

{
resolve: {
  modules: [...],
  fallback: {
    "fs": "browserify-fs",

Then, we can have new errors at the run time (using serve after build).

Our solution:

  • We just removed all @/ aliases from our app.
  • Limit what we import from payload or payload/dist and duplicate types in our repository when possible.
  • Empty webpack config but we still need browserfied packages like : "browserify-fs": "^1.0.0",.

I don’t know why I can have issues relative to SCSS setup or browserified-fs when I import things from payload/dist/payload.

Do we have a way to be sure that when importing things like types, 20% of all payloadCMS bundle is not also included ?

I manage to track down the issue. The problem is that when the config is Loaded in NodeJS on server side, it will require the compiled Component jsx files. Some of these files contain a require call to SCSS resources to bundle them in webpack, but this will fail on server side.

I managed to add a workaround with intercept-require and return an empty object for these resources, but this is a bit dirty.

@JessChowdhury yes, my case is solved.