Code Monkey home page Code Monkey logo

carbon-preprocess-svelte's Introduction

carbon-preprocess-svelte

NPM GitHub npm downloads to date

Svelte preprocessors for the Carbon Design System

Installation

Install carbon-preprocess-svelte as a development dependency.

# Yarn
yarn add -D carbon-preprocess-svelte

# npm
npm i -D carbon-preprocess-svelte

# pnpm
pnpm i -D carbon-preprocess-svelte

Usage

  • optimizeImports: Svelte preprocessor that rewrites Carbon Svelte imports to their source path in the script block, making development compile times dramatically faster.
  • optimizeCss: Vite/Rollup plugin that removes unused Carbon styles, resulting in smaller CSS bundles.

optimizeImports

optimizeImports is a Svelte preprocessor that rewrites barrel imports from Carbon components/icons/pictograms packages to their source Svelte code paths. This can significantly speed up development and production build compile times while preserving typeahead and autocompletion offered by integrated development environments (IDE) like VS Code.

The preprocessor optimizes imports from the following packages:

- import { Button } from "carbon-components-svelte";
+ import Button from "carbon-components-svelte/src/Button/Button.svelte";

- import { Add } from "carbon-icons-svelte";
+ import Add from "carbon-icons-svelte/lib/Add.svelte";

- import { Airplane } from "carbon-pictograms-svelte";
+ import Airplane from "carbon-pictograms-svelte/lib/Airplane.svelte";

Note

When this preprocessor was first created, there was no workaround to optimize slow cold start times with Vite in development. As of today, @sveltejs/vite-plugin-svelte enables prebundleSvelteLibraries, which pre-bundles Svelte libraries to improve cold start times for Vite-based set-ups. However, this preprocessor is still useful for non-Vite bundlers, like Rollup and Webpack.

SvelteKit

See examples/sveltekit.

// svelte.config.js
import adapter from "@sveltejs/adapter-static";
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
import { optimizeImports } from "carbon-preprocess-svelte";

/** @type {import('@sveltejs/kit').Config} */
const config = {
  preprocess: [
    // Preprocessors are run in sequence.
    // If using TypeScript, the code must be transpiled first.
    vitePreprocess(),
    optimizeImports(),
  ],
  kit: {
    adapter: adapter(),
  },
};

export default config;

Vite

See examples/vite.

// vite.config.js
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
import { optimizeImports } from "carbon-preprocess-svelte";

/** @type {import('vite').UserConfig} */
export default {
  plugins: [
    svelte({
      preprocess: [
        // Preprocessors are run in sequence.
        // If using TypeScript, the code must be transpiled first.
        vitePreprocess(),
        optimizeImports(),
      ],
    }),
  ],
};

Rollup

This code is abridged; see examples/rollup for a full set-up.

// rollup.config.js
import svelte from "rollup-plugin-svelte";
import { optimizeImports } from "carbon-preprocess-svelte";

export default {
  plugins: [
    svelte({
      preprocess: [optimizeImports()],
    }),
  ],
};

Webpack

This code is abridged; see examples/webpack for a full set-up.

// webpack.config.js
const { optimizeImports } = require("carbon-preprocess-svelte");

module.exports = {
  module: {
    rules: [
      {
        test: /\.svelte$/,
        use: {
          loader: "svelte-loader",
          options: {
            hotReload: !PROD,
            preprocess: [optimizeImports()],
            compilerOptions: { dev: !PROD },
          },
        },
      },
    ],
  },
};

optimizeCss

optimizeCss is a Vite plugin that removes unused Carbon styles at build time. The plugin is compatible with Rollup (Vite extends the Rollup plugin API).

[email protected] or greater is required.

$ vite build

Optimized index-CU4gbKFa.css
- Before: 606.26 kB
+ After:   53.22 kB (-91.22%)

dist/index.html                  0.34 kB │ gzip:  0.24 kB
dist/assets/index-CU4gbKFa.css  53.22 kB │ gzip:  6.91 kB
dist/assets/index-Ceijs3eO.js   53.65 kB │ gzip: 15.88 kB

Note

This is a plugin and not a Svelte preprocessor. It should be added to the list of vite.plugins. For Vite set-ups, this plugin is only run when building the app. For Rollup and Webpack, you should conditionally apply the plugin to only execute when building for production.

SvelteKit

See examples/sveltekit.

// vite.config.js
import { sveltekit } from "@sveltejs/kit/vite";
import { optimizeCss } from "carbon-preprocess-svelte";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [sveltekit(), optimizeCss()],
});

Vite

See examples/vite.

// vite.config.js
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { optimizeCss } from "carbon-preprocess-svelte";

/** @type {import('vite').UserConfig} */
export default {
  plugins: [svelte(), optimizeCss()],
};

Rollup

This code is abridged; see examples/rollup for a full set-up.

// rollup.config.js
import svelte from "rollup-plugin-svelte";
import { optimizeCss } from "carbon-preprocess-svelte";

const production = !process.env.ROLLUP_WATCH;

export default {
  plugins: [
    svelte({
      preprocess: [optimizeImports()],
    }),

    // Only apply the plugin when building for production.
    production && optimizeCss(),
  ],
};

Webpack

Webpack users should use the OptimizeCssPlugin. The plugin API is identical to the Vite plugin.

This code is abridged; see examples/webpack for a full set-up.

// webpack.config.js
const { OptimizeCssPlugin } = require("carbon-preprocess-svelte");

const PROD = process.env.NODE_ENV === "production";

module.exports = {
  plugins: [
    // Only apply the plugin when building for production.
    PROD && new OptimizeCssPlugin(),
  ],
};

optimizeCss API

optimizeCss({
  /**
   * By default, the plugin will print the size
   * difference between the original and optimized CSS.
   *
   * Set to `false` to disable verbose logging.
   * @default true
   */
  verbose: false,

  /**
   * By default, pre-compiled Carbon StyleSheets ship `@font-face` rules
   * for all available IBM Plex fonts, many of which are not actually
   * used in Carbon Svelte components.
   *
   * The default behavior is to preserve the following IBM Plex fonts:
   * - IBM Plex Sans (300/400/600-weight and normal-font-style rules)
   * - IBM Plex Mono (400-weight and normal-font-style rules)
   *
   * Set to `true` to disable this behavior and
   * retain *all* IBM Plex `@font-face` rules.
   * @default false
   */
  preserveAllIBMFonts: false,
});

Examples

Refer to examples for common set-ups.

Contributing

Refer to the contributing guidelines.

License

Apache 2.0

carbon-preprocess-svelte's People

Contributors

gschurck avatar metonym avatar stevemar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

carbon-preprocess-svelte's Issues

Svelte 4 compatibility for peer dependencies

I get this message when updating to Svelte 4:

WARN Issues with peer dependencies found
.
└─┬ carbon-preprocess-svelte 0.9.1
  └─┬ svelte-preprocess 4.10.7
    └── ✕ unmet peer svelte@^3.23.0: found 4.0.0

My svelte-preprocess version in package.json is ^5.0.4.

optimizeCarbonImports breaks sveltekit hydration

I tried to port my app from routify to sveltekit, and I noticed that when I add optimizeCarbonImports in the preprocess sectionm of my config the componenets would not hydrate in production but still work normally in local development

/** @type {import('@sveltejs/kit').Config} */
import { icons, optimizeCss, elements, optimizeCarbonImports } from 'carbon-preprocess-svelte'
import vercel from '@sveltejs/adapter-vercel'

const config = {
  preprocess: [optimizeCarbonImports(),elements(), icons()],
  kit: {
    target: '#svelte',
    ssr: false,
    trailingSlash: 'never',
    vite: {
      plugins: [optimizeCss()],
    },
    adapter: vercel(),
    prerender: {
      enabled: false,
    },
  },
}

export default config

ParseError with scss inside component

There is a problem during build with optimizeCss, when the scss is inside a component's style tag.

Here is the error:

[plugin-optimize-css] Selector is expected
file: /home/jeremy/app/front/src/lib/Uploads.svelte
125:   @import '../styles/vars';
126:
127:   $position: fixed;
       ^
128:
129:   .container {
error during build:
ParseError: Selector is expected
    at error (file:///home/jeremy/app/node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/carbon-preprocess-svelte/dist/index.mjs:19062:18)

It does not recognize nested styles either.

Here is my relevant vite config:

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import sveltePreprocess from 'svelte-preprocess'
import viteCompression from 'vite-plugin-compression'
import { optimizeCss, optimizeImports } from 'carbon-preprocess-svelte'

export default defineConfig(({ mode }) => {
	const prod = mode === 'production'
	return {
		plugins: [
			svelte({
				preprocess: [sveltePreprocess({ scss: true }), optimizeImports()],
				emitCss: prod,
			}),
			prod && optimizeCss(),
			prod && viteCompression({ algorithm: 'brotliCompress', ext: '.br' }),
			prod && viteCompression({ algorithm: 'gzip' }),
		],
		build: {
			minify: prod,
		}
	}
})

I think the plugins order is allright.
I do not have any problem during development as my style tags does have lang="scss" for proper preprocessing.

The interesting thing is that the build works fine when the scss is external:

<style lang="scss" src="./container.scss"></style>

Does anybody have a clue ?

Using optimizeImports() with SvelteKit causes error 500 `Unexpected token 'export'`

Description

I'm trying out Carbon for the first time, and hoping to use it with SvelteKit. I had some success with adding some first components without a pre-processor, but the vite dev server was struggling to generate everything and pages were taking over a minute to load with components and icons. As such, I turned to the pre-processor, but ran into an issue where it caused page renders to fail. Below are the steps I followed reproduce this issue (used the sveltekit example as a template).

Steps to Reproduce

  1. npm create svelte@latest test-app
    • Skeleton Project
    • Yes, using TypeScript syntax
    • ESLint: yes
    • Prettier: yes
    • Playwright: no
  2. cd test-app
  3. npm install
  4. npm i -D carbon-components-svelte carbon-preprocess-svelte
  5. Edit ./src/routes/index.svelte
    • Add the following:
      <script>
          import "carbon-components-svelte/css/g100.css";
          import { Button, truncate } from "carbon-components-svelte";
      </script>
      
      <Button>Primary button</Button>
      
      <div use:truncate>Text...</div>
      
  6. Edit ./svelte.config.js
    • Adjust to match:
      import adapter from '@sveltejs/adapter-auto';
      import preprocess from 'svelte-preprocess';
      import { optimizeImports } from 'carbon-preprocess-svelte';
      
      /** @type {import('@sveltejs/kit').Config} */
      const config = {
      	// Consult https://github.com/sveltejs/svelte-preprocess
      	// for more information about preprocessors
      	preprocess: [preprocess(), optimizeImports()],
      
      	kit: {
      		adapter: adapter()
      	}
      };
      
      export default config;
      
  7. npm run dev

Actual Outcome

From there, the following error is found in the browser and the console:

500
Unexpected token 'export'
.\test-app\node_modules\carbon-components-svelte\src\Truncate\truncate.js:9
export function truncate(node, options = {}) {
^^^^^^

SyntaxError: Unexpected token 'export'
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1032:15)
    at Module._compile (node:internal/modules/cjs/loader:1067:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:168:29)
    at ModuleJob.run (node:internal/modules/esm/module_job:195:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:337:24)

This issue goes away if optimizeImports() is removed, or if import { truncate } is removed. I haven't tested enough to know if it's also an issue for other function imports.

Relevant Versions

Node: v16.14.0

@sveltejs/kit: 1.0.0-next.377
svelte: 3.49.0

carbon-components-svelte: 0.67.1
carbon-preprocess-svelte: 0.9.1

[plugin-optimize-css] TypeError: PurgeCSS is not a constructor

Im back :v This time I get the error PurgeCSS is not a constructor.

Not sure what that's about but it might be related to FullHuman/purgecss#276 or FullHuman/purgecss#43

$ npm run build

> [email protected] build
> routify -b && svelte-check && vite build

[Routify] Generated routes in 0 ms

Loading svelte-check in workspace: c:\Users\LinkPlay\dev\first-prototype\FrontEnd
Getting Svelte diagnostics...
====================================

====================================
svelte-check found 0 errors, 0 warnings and 0 hints
vite v2.2.4 building for production...
✓ 126 modules transformed.
rendering chunks (13)...[plugin-optimize-css] PurgeCSS is not a constructor
error during build:
TypeError: PurgeCSS is not a constructor
    at Object.generateBundle (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\carbon-preprocess-svelte\dist\index.js:72991:40)
    at C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\rollup\dist\shared\rollup.js:18918:25

Sorry for bringing the next bug. Could also be something wrong with my setup so if you want any configs hit me up.
Cheers 😄

Generic support for other libraries

I ran into the same problem this preprocessor is solving in another library and was just pointed here. Wow. This is a pretty ingenious solution! I couldn't come up with any answer I liked myself

I think it could be recommended for all projects in the SvelteKit FAQ. Possibly it could even be included in SvelteKit by default until / unless another solution is built in

I was wondering, is there anything Carbon-specific about it? Maybe it could be called something more general like carbon-design-system/fast-imports-preprocessor?

Unexpected Token Error when importing types

Hello, I have had a bug when importing typescript types in Svelte components:

<script lang="ts">
    import type { MyType } from './MyType'
    // ...
</script>

<h1>Welcome</h1>

The import statement in MyComponent.svelte throws an Unexpected token error.

After some search, I figured out this error is thrown whenever icons() and/or pictograms() preprocessors are used in svelte.config.js. It is this particular issue that led me thinking that carbon processors might be involved in the error.

Steps to reproduce the bug

  1. Install new sveltekit project
npm init svelte@next my-app
cd my-app
npm install
  1. Modify project code and declare new type to import

2.1 Create new file my-app/src/routes/MyType.d.ts

export type MyType = {
    name: string;
}

2.2 Import type in my-app/src/routes/index.svelte

<script lang="ts">
    import type { MyType } from './MyType'
    let a = {} as MyType;
</script>

<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

At this point, everything should work as expected.

  1. Install carbon tools
npm i -D carbon-components-svelte carbon-preprocess-svelte carbon-icons-svelte
npm install
  1. Change svelte.config.js to include carbon preprocesses
import adapter from '@sveltejs/adapter-auto';
import preprocess from 'svelte-preprocess';
import { optimizeImports, elements, icons, pictograms } from 'carbon-preprocess-svelte';

/** @type {import('@sveltejs/kit').Config} */
const config = {
	// Consult https://github.com/sveltejs/svelte-preprocess
	// for more information about preprocessors
	preprocess: [preprocess(), optimizeImports(), elements(), icons(), pictograms()],

	kit: {
		adapter: adapter()
	}
};

export default config;

It is this last step that causes the bug

Workaround

Removing both icons() and pictograms() fixes the bug.

Thank you for your time and help.

rgba hex value warning

I keep getting the following logged during npm run check and npm run build and it's unclear what's causing it, curious if anyone else ran into similar messages:

====================================
Loading svelte-check in workspace: /Users/mark/src/svelte-app
Getting Svelte diagnostics...

[carbon:elements] rgba hex value must be six characters. Received "#0"
[carbon:elements] rgba hex value must be six characters. Received "#0"
====================================
svelte-check found 0 errors, 0 warnings, and 0 hints

[bug, sveltekit] ParseError: Colon is expected

On debug and build, I have this error:

ParseError: Colon is expected
    at error (file:///home/grandnainconnu/Documents/projects/work/LesEchoppes/[hidden]/node_modules/carbon-preprocess-svelte/dist/index.mjs:19062:18)
    at Parser$1.error (file:///home/grandnainconnu/Documents/projects/work/LesEchoppes/[hidden]/node_modules/carbon-preprocess-svelte/dist/index.mjs:19136:5)
    at Object.read_style [as read] (file:///home/grandnainconnu/Documents/projects/work/LesEchoppes/[hidden]/node_modules/carbon-preprocess-svelte/dist/index.mjs:15607:15)
    at tag (file:///home/grandnainconnu/Documents/projects/work/LesEchoppes/[hidden]/node_modules/carbon-preprocess-svelte/dist/index.mjs:18272:29)
    at new Parser$1 (file:///home/grandnainconnu/Documents/projects/work/LesEchoppes/l[hidden]/node_modules/carbon-preprocess-svelte/dist/index.mjs:19096:15)
....

This error is related to the Loader component (see bellow), but I can't understand why.
If you can help,

import path from 'path';

import node from '@sveltejs/adapter-node';
import * as carbon from 'carbon-preprocess-svelte';

import preprocess from 'svelte-preprocess';

const { typescript } = preprocess;

export default {
    preprocess: [typescript(), ...carbon.presetCarbon()],
    kit: {
        adapter: node({}),
        ssr: true,
        target: '#svelte',
        vite: {
            optimizeDeps: {
                include: ['clipboard-copy'],
            },
            plugins: [process.env.NODE_ENV === 'production' && carbon.optimizeCss()],
            resolve: {
                alias: {
                    $components: path.resolve('./src/components'),
                    $forms: path.resolve('./src/forms'),
                    $communication: path.resolve('./src/communication'),
                },
            },
        },
    },
};

__layout.svelte:

<script lang="ts">
	import { prerendering } from '$app/env';

	import Loader from '$components/Loader.svelte';
</script>

{#if prerendering}
	<Loader />
{:else}
	<slot />
{/if}

<style lang="scss" global>
	@import "carbon-components-svelte/css/g10";
</style>

Loader.svelte:

<div class="loader">
    <img src='/assets/images/logo.svg' width="80" height="80" alt="Loading" />
</div>

<style lang="scss">
    .loader {
        width: 100%;
        height: 100%;

        margin-top: 20px;
        margin-bottom: 40px;

        display: flex;
        align-items: center;
        justify-content: center;

        img {
            animation: rotateSqueeze 1s linear infinite;
        }

        @keyframes rotateSqueeze {
            from, to {
                transform: translateY(0px) scale(1, 1);
            }
            25% {
                transform: translateY(-20px) scale(1.25, 0.80);
            }
            75% {
                transform: translateY(20px) scale(0.80, 1.25);
            }
        }
    }
</style>

optimizeCss v0.11.0 breaks image styling on production builds with Sveltekit

Environment

Device and OS: Macbook Pro 16, Sonoma 14.3.1, Google Chrome Version 123.0.6312.86 (Official Build) (arm64)
App/package versions:
carbon-preprocess-svelte: v0.11.0
carbon-components-svelte: 0.85.0
svelte: 4.2.12

Steps to reproduce

  1. Import optimizeCSS in accordance with docs
  2. Run a production build: npm run build
  3. View application in browser (recommend clear cache and hard reload)
  4. Images no longer have styling applied to them and are full screen.

Example code affected:

	<div class="logo">
		<img alt="Logo" src={logo} class="logo" />
	</div>

<style lang="scss">
	.logo {
		width: 252px;
		height: 72px;
	}
</style>

I confirmed that removing the optimizeCSS plugin and rebuilding fixes the images and they display as expected.

I also noticed some other components other than images were affected. We have SideNavMenuItems with an OverflowMenu in them that was no longer styled correctly. This component has a lot of overrides of default Carbon classes, but the optimizeCSS plugin seems to have affected those overrides.

Running locally in development mode (npm run dev), images are not affected.

Screenshots of side nav items

Without optimizeCSS:

Screenshot 2024-03-27 at 9 51 08 AM

With optimizeCSS:

Screenshot 2024-03-27 at 9 50 20 AM

optimizeImports() seemingly creates invalid source maps

I originally posted this on stack overflow thinking I was doing something wrong: https://stackoverflow.com/questions/69548571/svelte-carbon-component-import-breaks-debugging

Bug according to the first answer, it looks like the optimizeImports() plugin is producing bad source maps. I've created a repo that reproduces the issue here:

https://github.com/troncoso/carbon-svelte-bug

As the README says, if you remove the call to optimizeImports(), then breakpoints work correctly. The stack overflow answer has in depth information on what is believed to be wrong

Docs and e2e examples are out of date

Related #44

In addition to updating the SvelteKit example (and perhaps converting it to TypeScript), it would also be useful to add a plain Vite example to verify that the README instructions actually work.

Notification breaks optimizeCss()

spliced strings unexpectedly retain all styles

https://github.com/carbon-design-system/carbon-components-svelte/blob/c87196c16b344e041cf002f0d51a7c738eacb5d0/src/Notification/NotificationIcon.svelte#L34-L39

<svelte:component
  this="{icons[kind]}"
  size="{20}"
  title="{iconDescription}"
  class="bx--{notificationType}-notification__icon"
/>

https://github.com/carbon-design-system/carbon-components-svelte/blob/c87196c16b344e041cf002f0d51a7c738eacb5d0/src/Notification/NotificationButton.svelte#L39-L45

  <svelte:component
    this="{icon}"
    size="{20}"
    title="{title}"
    class="bx--{notificationType}-notification__close-icon"
  />
</button>

compile result

function switch_props(ctx) {
  return {
    props: {
      size: 20,
      title: /*iconDescription*/ ctx[2],
      class: "bx--" + /*notificationType*/ ctx[1] + "-notification__icon",
    },
  };
}

Got Error: Unexpected option config.kit.vite when execute yarn dev

I set optimizeCss() up svelte.config.js following the guide with README.md like this.

import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/kit/vite';
import { optimizeCss, optimizeImports } from 'carbon-preprocess-svelte';

/** @type {import('@sveltejs/kit').Config} */
export default {
  preprocess: [vitePreprocess(), optimizeImports()],

  kit: {
    adapter: adapter(),
    vite: {
      plugins: [process.env.NODE_ENV === "production" && optimizeCss()],
    },
  }
};

And when I execute yarn dev or yarn preview I get the following error.

error when starting dev server:
Error: Unexpected option config.kit.vite

Here is my package.json

	"devDependencies": {
		"@sveltejs/adapter-auto": "^2.0.0",
		"@sveltejs/adapter-node": "^1.2.3",
		"@sveltejs/kit": "^1.5.0",
		"carbon-components-svelte": "^0.75.1",
		"carbon-icons-svelte": "^11.4.0",
		"carbon-preprocess-svelte": "^0.9.1",
		"svelte": "^3.54.0",
		"svelte-check": "^3.0.1",
		"ts-node": "^10.9.1",
		"tslib": "^2.4.1",
		"tsx": "^3.12.7",
		"typescript": "^5.0.3",
		"vite": "^4.2.0",
	},
	"type": "module",

How can I fix this problem?

`optimizeCss` should not print diff if there was no diff

In the following output, optimizeCss did not modify the second CSS asset, so it should not print anything.

Optimized assets/index-Dy43zAwI.css
Before: 750.82 kB
After:  336.35 kB (-55.2%)



Optimized assets/CodeHighlighter-1BpQ5oIG.css
Before: 2.3 kB
After:  2.3 kB (-0%)

Run optimizeImports for all imports on dev server start

Hello, when I do npm install in my project to install a new dependency or update another dependency the .vite/deps/ folder gets deleted. It then gets added when I run npm run dev again.

The problem I now get with optimizeImports() is that it only optimizes the imports when I go to the SvelteKit route that has the import. The issue I'm now facing is that the request to fetch the optimized imports fails because of a timeout:
Screenshot from 2022-11-16 13-15-05

And because it fails I get redirected back to the route I came from. Then when I try to go to the route again it works because now they have been optimized.
Screenshot from 2022-11-16 13-15-56

It feels like the optimization of the import isn't fast enough for SvelteKit to get the optimized version in .vite/deps and therefore times out.

Do I miss some setting in my svelte/vite config? (See them below)

And is it at all possible to optimize all imports (if we have to) when we start the dev server?

I would also like to add that I had no issue with this when I ran SvelteKit version 405 (very old version without the new routing stuff). But updating to the latest version gave me this issue.

// svelte.config.js
import preprocess from 'svelte-preprocess';
import adapter from '@sveltejs/adapter-static';
import { optimizeImports } from 'carbon-preprocess-svelte';

const config = {
  preprocess: [
    preprocess({
      scss: {
        includePaths: ['./src/styles/'],
        data: '@import "index.scss;"'
      }
    }),
    optimizeImports()
  ],
  kit: {
    adapter: adapter({
      pages: 'build',
      assets: 'build',
      fallback: '404.html'
    })
  },
  ...
};
// vite.config.js
import { sveltekit } from '@sveltejs/kit/vite';
import { resolve } from 'path';
import wasmPack from 'vite-plugin-wasm-pack';

const config = {
  define: {
    'process.env': process.env
  },
  resolve: {
    alias: {
      $components: resolve('./src/components'),
      $stores: resolve('./src/stores'),
      $types: resolve('./src/types')
    }
  },
  plugins: [sveltekit(), wasmPack('./sie-parser-wasm')],
  ssr: {
    noExternal: ['@df/common']
  },
  server: {
    port: 3000,
    strictPort: true
  }
};

Request fix optimizeImport module support carbon-icon-component v12

Since Svelte 4 was released, carbon-component-svelte was also upgraded a few days ago, I would like to request we upgrade the component to support icon v12.

For now in code only validate package icon prefix v11. When meet v12 it fell to an old icon component link and broken site.

Optimize Css problem

Hi, i follow the guide and put the optimizeCss() in vite config, it actually work from 700kb to 158kb, but the problem is that i actually lose the Theme toggle and the nav bar submenus.

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import { optimizeImports, optimizeCss, elements, icons } from "carbon-preprocess-svelte";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [svelte(), optimizeImports(), elements({ theme: "all" }), icons()],
  base: ""
})

i take it off in the code and now everything work but the css bundle is really hight

Using optimizeCss with tailwind breaking css in sveltekit.

After using optimizeCss, CSS size is decreased but tailwind styles are not working ( but some are applying ) when running yarn preview. Especially md:flex, md:pt-4 and lg:mb-3 etc styles are not working.

Then removed optimizeCss and after build CSS size is not decreased but tailwind all styles are applying.

`optmizeCss` has no effect on build size

Hi @metonym , thank you for your work on Svelte and Carbon.

I would appreciate your help with the following setup:

  • vite.config.js
import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { optimizeCss } from "carbon-preprocess-svelte";

export default defineConfig({
  plugins: [
    svelte(),
    optimizeCss(),
  ],
  build: {
    lib: {
      name: "Button",
      entry: "src/Main.svelte",
      fileName: "index",
    },
  },
});
  • Css.svelte
<style global lang="postcss">
  @import "carbon-components-svelte/css/white";
  @import "tailwindcss/base";
  @import "tailwindcss/components";
  @import "tailwindcss/utilities";
</style>
  • Main.svelte
<script lang="ts">
  import "./Css.svelte";
  export let label: string;
</script>

<button type="button" class="btn">
  {label}
</button>

<style lang="postcss">
  .btn {
    @apply font-bold;
  }
</style>

The Carbon theme is not used at all but ends up included in the final style.css. Tailwind is correctly purged. I believe the plugin is not being triggered but I cannot figure out what I'm doing wrong. Could you point me in the right direction?

`optimizeImports` incompatible with Carbon icons v11

Named imports are no longer resolved correctly with the structure of v11.

E.g.

import { BrightnessContrast, Tools, ... } from 'carbon-icons-svelte';

Results in errors like:

Module not found: Error: Can't resolve 'carbon-icons-svelte/lib/BrightnessContrast/BrightnessContrast.svelte' in '...'

(The same thing happens for optimizeCarbonImports from 'carbon-components-svelte/preprocess')

[plugin-optimize-css] Unexpected token when using TypeScript in Script Block

Interested in using the optimizeCss Plugin for production I added it to my vite.config.js. I'm using TypeScript in most Script Blocks and I got this error:

$ npm run build

> [email protected] build
> routify -b && svelte-check && vite build

[Routify] Generated routes in 0 ms

Loading svelte-check in workspace: c:\Users\LinkPlay\dev\first-prototype\FrontEnd
Getting Svelte diagnostics...
====================================

====================================
svelte-check found 0 errors, 0 warnings and 0 hints
vite v2.2.4 building for production...
✓ 26 modules transformed.
[plugin-optimize-css] Unexpected token
file: C:/Users/LinkPlay/dev/first-prototype/FrontEnd/src/pages/matches/[matchId]/watch.svelte
11:   import GameRunner from "./_components/GameRunner.svelte";
12: 
13:   export let matchId: string;
                        ^
14: 
15:   let matchPromise = getMatch(matchId);
error during build:
ParseError: Unexpected token
    at error (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\carbon-preprocess-svelte\dist\index.js:19004:18)
    at Parser$1.error (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\carbon-preprocess-svelte\dist\index.js:19078:5)
    at Parser$1.acorn_error (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\carbon-preprocess-svelte\dist\index.js:19072:10)        
    at Object.read_script [as read] (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\carbon-preprocess-svelte\dist\index.js:11539:13)
    at tag (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\carbon-preprocess-svelte\dist\index.js:18214:29)
    at new Parser$1 (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\carbon-preprocess-svelte\dist\index.js:19038:15)
    at parse$3 (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\carbon-preprocess-svelte\dist\index.js:19168:19)
    at extractSelectors (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\carbon-preprocess-svelte\dist\index.js:72052:15)
    at Object.transform (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\carbon-preprocess-svelte\dist\index.js:72144:27)
    at async ModuleLoader.addModuleSource (C:\Users\LinkPlay\dev\first-prototype\FrontEnd\node_modules\rollup\dist\shared\rollup.js:18451:30)    

Hope I didn't raise the alarm too soon. Just letting you guys know. I'm just very glad that you are working on a optimizeCss Plugin 😄 👐

Some styles are lost after optimizeCss()

I am using sveltekit with carbon. In dev mode everything is working, but after build with optimizeCss() some styles are lost (h2, SideNavMenu, etc).
Without optimizeCss():

    font-size: 2rem;
    font-weight: 400;
    line-height: 1.25;
    letter-spacing: 0;

Can't see a way to optimize imports when not importing in a svelte file

I'm working on a sveltekit project using TypeScript, I have a library that generates data for navigation and this includes icons for some of the items.

If I import the icon in the same fashion as in a svelte file, you get the same problem that would occur when not using optimizeImports in your preprocess section (i.e. a huge number of carbon components all being requested .

Currently my workaround is to use import Home16 from 'carbon-icons-svelte/lib/Home16/Home16.svelte' rather than the nicer import Home16 from 'carbon-icons-svelte'.

Is it there an optimizeNonSvelteFileImports equivalent?

Compatibility issues with Svelte 5

Although Svelte 5 is not yet released, it's in active development and preview and I thought it might be useful to get an early signal on this.

I set up a new project with create-svelte and chose the "Svelte 5 Preview" option during setup. I then installed carbon-components-svelte and carbon-preprocess-svelte.

After updating my svelte.config.js with the change specified in the README, I saw this error in the console:

6:59:46 PM [vite] Pre-transform error: Error while preprocessing /home/casey/osu-embeddings/frontend/.svelte-kit/generated/root.svelte - 'svelte/compiler' no longer exports a `walk` utility — please import it directly from 'estree-walker' instead
6:59:46 PM [vite] Error when evaluating SSR module /.svelte-kit/generated/root.js: failed to import "/.svelte-kit/generated/root.svelte"
|- Error: Error while preprocessing /home/casey/osu-embeddings/frontend/.svelte-kit/generated/root.svelte - 'svelte/compiler' no longer exports a `walk` utility — please import it directly from 'estree-walker' instead
    at e.walk (/home/casey/osu-embeddings/frontend/node_modules/svelte/compiler/index.js:1:676168)
    at script (/home/casey/osu-embeddings/frontend/node_modules/carbon-preprocess-svelte/dist/preprocessors/optimize-imports.js:32:33)
    at process_single_tag (file:///home/casey/osu-embeddings/frontend/node_modules/svelte/src/compiler/preprocess/index.js:280:27)
    at file:///home/casey/osu-embeddings/frontend/node_modules/svelte/src/compiler/preprocess/replace_in_code.js:30:4
    at String.replace (<anonymous>)
    at calculate_replacements (file:///home/casey/osu-embeddings/frontend/node_modules/svelte/src/compiler/preprocess/replace_in_code.js:28:9)
    at replace_in_code (file:///home/casey/osu-embeddings/frontend/node_modules/svelte/src/compiler/preprocess/replace_in_code.js:69:29)
    at process_tag (file:///home/casey/osu-embeddings/frontend/node_modules/svelte/src/compiler/preprocess/index.js:297:32)
    at Module.preprocess (file:///home/casey/osu-embeddings/frontend/node_modules/svelte/src/compiler/preprocess/index.js:357:31)
    at async compileSvelte (file:///home/casey/osu-embeddings/frontend/node_modules/@sveltejs/vite-plugin-svelte/src/utils/compile.js:89:20)

It looks like these imports:

import { parse, walk } from "svelte/compiler";

Will need to be updated to work with Svelte v5. I'm not sure if there are other compat issues as well beyond these.

Anyway, this isn't a big problem right now because Svelte 5 is still not yet officially released - but yeah I wanted to give a heads up!

HeaderSearch has wrong styling when compiled

I am using a HeaderSearch component to include a search bar in my global header bar on top. When running svelte in local development, everything works properly and looks like this:

Screen Shot 2021-12-23 at 2 24 53 PM

That is the right half of the browser window at the top of the page. Here it is expanded:
Screen Shot 2021-12-23 at 2 25 34 PM

When I use npm run build and host it on Netlify, the HeaderSearch component is missing quite a few styles and looks like this:
Screen Shot 2021-12-23 at 2 30 44 PM

And here it is extended:
Screen Shot 2021-12-23 at 2 31 08 PM

I had run into a few, other minor differences between local & prod before, but nothing like this. Maybe something is not configured properly? I would love some pointers to figure out what's causing the differences here.

optimizeCss removes carbon-charts css

Hello,
I tried carbon-charts and wondered why it had missing css even though I imported the css file. It turns out that it was caused by optimizeCss(). Nevertheless, I can work around it by importing stylesheet from html head.

This library needs a rewrite

Tons of issues:

  • like optimizeCss is hit-or-miss and no longer working for SvelteKit/Vite
  • new Svelte 4 breaking changes
  • preprocessors don't return a source map (which affects how IDE language servers work)
  • versions get out-of-sync; is there a way where this library does not have to be bumped if carbon-components-svelte changes?

Narrow the scope:

  • Preprocessors:
    • Single preprocessor to optimize components/icons/pictograms; do not support v10 import paths
    • Drop all other preprocessors, except for elements, which has potential
    • Elements preprocessor should look beyond just the style block, and include script/markup
  • Build: do not use esbuild to compile the library. Simply use tsc.

Minor dependency update breaks this package

Not sure what went wrong here. Ran a batch of dependency updates (minor versions only) and suddenly seeing this error when building:

Error: Could not find a declaration file for module 'carbon-preprocess-svelte'. 'node_modules/carbon-preprocess-svelte/dist/index.mjs' implicitly has an 'any' type.

In my svelte.config.js I'm importing it like this:

import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import { optimizeImports, optimizeCss, icons } from 'carbon-preprocess-svelte';

This is the diff:

Screenshot 2024-02-27 at 21 02 52

I assume this package is not at fault but wanted to post it here for visibility.

`elements` cannot process CSS variables

Bug

In a project making use of the elements preprocessor, an error is thrown when adding a CSS variable:

Cannot read properties of undefined (reading 'some')
file: redacted
error during build:
TypeError: Error while preprocessing redacted.svelte - Cannot read properties of undefined (reading 'some')

The stack trace points to this line:

const hasOperator = child.value.children.some(
(child, index) => index > 0 && child.type === "Operator"
);

Reproduction

https://stackblitz.com/edit/sveltejs-kit-carbon-preprocess?file=src%2Froutes%2F%2Bpage.svelte

Add any custom class with a custom CSS variable, and the app will crash:

:root {
  --my-bg: black;
}
.test {
  background-color: var(--my-bg);
  color: white;
}

If you can help with a proposed solution, I'm willing to contribute a PR.

Update docs on usage

Vite should already prebundle libraries, including those for Svelte. This comes at a cost of a longer cold start time (as it must), but overall is a better solution to using a preprocessor (which also comes at a cost).

  1. Vite users should be instructed to use prebundleSvelteLibraries (which should be enabled by default).
  2. Non-Vite set-ups could still benefit from a preprocessor (e.g., Rollup, Webpack).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.