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

Unable to properly ignore/exclude files for transformation #242

Open
marcus-sa opened this issue Sep 18, 2024 · 3 comments
Open

Unable to properly ignore/exclude files for transformation #242

marcus-sa opened this issue Sep 18, 2024 · 3 comments
Assignees
Labels
package: system Specific to @mui/system status: waiting for maintainer These issues haven't been looked at yet by a maintainer

Comments

@marcus-sa
Copy link

marcus-sa commented Sep 18, 2024

Steps to reproduce

I'm trying to use Pigment CSS in a project that uses decorators and TextDecoder/TextEncoder.
However this doesn't work because WYW-in-JS uses Babel.
If I add the @babel/plugin-proposal-decorators I now get an error saying that TextDecoder is not defined.
These files are part of separate libraries and not part of the main application.

Here's what I've tried without any luck:

Here's my vite.config.ts.

import { defineConfig } from 'vite';
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
import { vitePlugin as remix } from '@remix-run/dev';
import { remixPWA } from '@remix-pwa/dev';
import { join } from 'node:path';
import { workspaceRoot } from '@nx/devkit';
import tailwindcss from '@tailwindcss/vite';
import { pigment } from '@pigment-css/vite-plugin';
import { createTheme } from '@mui/material';
import { deepkitType } from '@deepkit/vite';

const buildDirectory = join(workspaceRoot, 'dist/apps/web');

const isProd = process.env.NODE_ENV === 'production';

const __dirname = import.meta.dirname;

const transformLibraries = ['@mui/material', '@mui/material-pigment-css', '@pigment-css/react'];

export default defineConfig({
  root: __dirname,
  base: './',
  cacheDir: join(workspaceRoot, 'node_modules/.vite/apps/web'),
  css: {
    transformer: 'lightningcss',
    lightningcss: {
      drafts: {
        customMedia: true,
      },
    },
  },
  plugins: [
    tailwindcss(),
    deepkitType({
      tsConfig: join(__dirname, 'tsconfig.json'),
      compilerOptions: {
        sourceMap: true,
      },
    }),
    remix({
      buildDirectory,
      future: {
        v3_fetcherPersist: true,
        v3_relativeSplatPath: true,
        v3_throwAbortReason: true,
        // unstable_singleFetch: true,
        unstable_optimizeDeps: true,
        unstable_lazyRouteDiscovery: true,
      },
    }),
    isProd &&
      remixPWA({
        buildVariables: {
          'process.env.REMIX_APP_VERSION': '',
          'process.env.MEDIA_HOST': '',
        },
      }),
    nxViteTsPaths({ buildLibsFromSource: !isProd }),
    pigment({
      transformLibraries: ['@mui/material'],
      theme: createTheme({
        cssVariables: {
          colorSchemeSelector: 'media',
        },
        defaultColorScheme: 'dark',
      }),
      // adding rules breaks the plugin
      rules: [
         {
           test: filename => !filename.endsWith('.tsx') &&
             !filename.endsWith('.css') &&
             !transformLibraries.some(packageName =>
               filename.includes(packageName),
             ),
           action: 'ignore',
         },
       ],
    }),
  ],
  build: {
    commonjsOptions: {
      include: ['@mui/utils', '@toolpad/core'],
    },
  },
  ssr: {
    noExternal: [/@mui/, /@pigment-css/, '@toolpad/core'],
  },
  server: { middlewareMode: true },
  test: {
    setupFiles: [join(__dirname, 'test-setup.ts')],
    watch: false,
    globals: true,
    environment: 'jsdom',
    include: [
      join(__dirname, 'tests/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'),
    ],
    reporters: ['default'],
    coverage: {
      reportsDirectory: join(workspaceRoot, 'coverage/apps/web'),
      provider: 'v8',
    },
  },
});

Search keywords: rules, decorators, exclude, ignore

@marcus-sa marcus-sa added the status: waiting for maintainer These issues haven't been looked at yet by a maintainer label Sep 18, 2024
@marcus-sa marcus-sa changed the title Vite plugin is unable to properly ignore/exclude files for transformation Plugin is unable to properly ignore/exclude files for transformation Sep 18, 2024
@marcus-sa marcus-sa changed the title Plugin is unable to properly ignore/exclude files for transformation Unable to properly ignore/exclude files for transformation Sep 18, 2024
@zannager zannager added the package: system Specific to @mui/system label Sep 18, 2024
@brijeshb42
Copy link
Contributor

You can also pass a list of babel plugins to pigment(). Something like -

pigment({
 babelOptions: {
   plugins: [...your pluginss],
 }
});

can you try this and let me know if it works

@marcus-sa
Copy link
Author

marcus-sa commented Oct 18, 2024

@brijeshb42 let you know if what works?

@sassanh
Copy link

sassanh commented Oct 18, 2024

I had to do some dirty hack to make pigment work with some files it was complaining about, something like this:

  babelOptions: {
    babelrc: true,
    plugins: [
      [
        "module-resolver",
        {
          alias: {
            "@": "./src",
            "@/lib/utils/enum": "./src/_empty",
          },
        },
      ],
    ],
  },

When _empty.ts is this:

const empty = {};

export default empty;

Its sole purpose is to replace files pigment complains about using module-resolver.

I also had to write this babel plugin for some other cases (like next-auth) to make pigment ignore them:

"use strict";

module.exports.__esModule = true;
module.exports.default = function ignoreModules({ types: t }) {
  return {
    visitor: {
      Program(path, state) {
        const { filename } = state.file.opts;
        const { entryPoints } = state.opts;

        if (entryPoints.some((entryPoint) => filename.endsWith(entryPoint))) {
          path.node.body = [
            t.variableDeclaration("const", [
              t.variableDeclarator(t.identifier("value"), t.valueToNode({})),
            ]),
            t.expressionStatement(
              t.assignmentExpression(
                "=",
                t.memberExpression(
                  t.identifier("module"),
                  t.identifier("exports"),
                ),
                t.identifier("value"),
              ),
            ),
          ];
        }
      },
    },
  };
};

But I think it's not needed when transformLibraries is set correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
package: system Specific to @mui/system status: waiting for maintainer These issues haven't been looked at yet by a maintainer
Projects
None yet
Development

No branches or pull requests

4 participants