Giter Site home page Giter Site logo

emosheeep / vite-plugin-lib-inject-css Goto Github PK

View Code? Open in Web Editor NEW
124.0 2.0 9.0 1.23 MB

Inject css at the top of chunk file in lib mode using import statement, support multiple entries.

Home Page: https://stackblitz.com/~/github.com/emosheeep/vite-plugin-lib-inject-css

License: MIT License

JavaScript 17.86% TypeScript 74.23% Vue 7.68% CSS 0.22%
build inject lib style vite vite-plugin

vite-plugin-lib-inject-css's People

Contributors

emosheeep avatar pmrotule avatar receter 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  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

vite-plugin-lib-inject-css's Issues

circular dependency scanner has a circular dependency

> ds
info Working directory is 
info Ignored paths: **/node_modules/**
❯ Globbing files with **/*.{js,ts,jsx,tsx,vue,mjs,cjs}
  ⠸ Wait a moment...
◼ Pulling out import specifiers from files...
◼ Analyzing circular dependencies...
ReferenceError: Cannot access '$' before initialization
    at AsyncHook.syncCwd (file:///C:/Users/m.ghaoui/AppData/Roaming/npm/node_modules/circular-dependency-scanner/node_modules/zx/build/core.js:324:5)
    at emitHook (node:internal/async_hooks:235:38)
    at promiseResolveHook (node:internal/async_hooks:364:3)
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
❯ Globbing files with **/*.{js,ts,jsx,tsx,vue,mjs,cjs}
  ⠦ Wait a moment...
◼ Pulling out import specifiers from files...
◼ Analyzing circular dependencies...

Error: Cannot find module '@ast-grep/napi-darwin-x64' in version 2.1.0

I'm updating from 2.0.1 to version 2.1.0, and I'm running into the error when building:

Cannot find module '@ast-grep/napi-darwin-x64' in version 2.1.0

When inspecting what gets installed between the 2.0 and 2.1 I see this:

Screen Shot 2024-05-11 at 7 22 51 AM

Screen Shot 2024-05-11 at 7 24 01 AM

This is in the index.cjs file from vite-plugin-lib-inject-css library.

I wonder if there is something that can be done on vite-plugin-lib-inject-css's end here, or if it is a config issue on my end.

I'm hoping to upgrade to this 2.1 version because it fixes the problem I'm having with use strict and the injected css file ending up on the same line.

Thanks so much for your help.

[Error] Cannot build Storybook with vite-plugin-lib-inject-css: TypeError "Cannot convert undefined or null to object"

I'm encountering an error when attempting to build static Storybook files using npm run build-storybook. The error message is:

TypeError: Cannot convert undefined or null to object
  at Function.values (<anonymous>)
  at configResolved (file:///C:/Github/infrastructure/node_modules/vite-plugin-dts/dist/index.mjs:743:100)
  ...

Relevant Dependencies:

{
  "vite": "^4.2.0",
  "storybook": "^7.0.23",
  "vite-plugin-lib-inject-css": "^1.3.0"
}

Additional Information:

  • The build process successfully ran when lib-inject-css is disabled

I'd appreciate any guidance on how to resolve this issue.

Thank you for your time and attention to this matter.

issue while building

i get this error while building ...

error during build:
RollupError: Plugin error - Unable to get file name for unknown file "OKEml5WQ".

sounds familiar ?

Check for deprecated rollupOptions.preserveModules

When rollupOptions.output.preserveModules is true, the association between a chunk and the css it referenced will lose for some reason, in which case style injection will be skipped.

It is possible to bypass this security check if the deprecated option rollupOptions.preserveModules is used.

Consider @import url()

Fantastic plugin...

I use this plugin in a library but the styles are external.... They are scss and your library still works.

If you can think of a workaround I can do a replace in all files for example.

Thanks.

vite-plugin-lib-inject-css not working on SSR

We are currently migrating our Vue component library from Rollup to Vite. We gave a try to vite-plugin-lib-inject-css which is working like a charm for the client assets, but it doesn't work for the server assets (build with the --ssr flag). It seems like it adds an import statement for the css file even though it doesn't exist (no CSS is generated on SSR which is expected).

I created a reproduction: https://stackblitz.com/edit/vue3-vite-starter-f7mk9t?file=dist%2Fserver%2FMyButton.mjs

Screenshot 2023-09-07 at 13 03 07

Of course, this breaks our SSR app that complains about the missing CSS files. One way to fix it would have been by using the SSR manifest generate with the --ssrManifest on client build, but it doesn't seem to work properly as the CSS file is sometimes missing. As you can see in my reproduction project, the entry HelloWorld doesn't have anything listed in the manifest:

image

So maybe vite-plugin-lib-inject-css could generate its own manifest and use it on SSR (e.g. by adding an option ssrManifestOutDir: '/absolute/path/to/dist/client' to retrieve the manifest on server build).

Can I suggest a solution by contributing a pull request? We are blocked by this issue so it's in our best interest to make it happen as soon as possible.

Thanks for the plugin by the way, it's a really nice solution to handle the CSS files 🙌

Injecting problematic js imports and making circular dependency

So I'm using vite-plugin-lib-inject-css inside my shared package in monorepo (internal lib), to inject css inside compiled vue js components. This works.

But I also have utils folder with helper functions which is also being built with vite, and this lib it seems, also injects component js files into that helpers file, making circular dep.

Here is my vite config:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import * as path from 'path';
import { libInjectCss, scanEntries } from 'vite-plugin-lib-inject-css';

export default defineConfig({
  plugins: [
    vue(),
    libInjectCss({
      formats: ['es'],
      entry: {
        index: 'src/index.ts', // Don't forget the main entry!
        ...scanEntries(['src/components']),
      },
    }),
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  build: {
    outDir: 'dist/assets',
    lib: {
      entry: 'src/index.ts',
      name: 'shared',
      formats: ['es'],
      fileName: (format) => `shared.${format}.js`,
    },
    rollupOptions: {
      // Make sure to externalize Vue and include it in your peerDependencies
      external: ['vue'],
      output: {
        // intro: 'import "./style.css";', // SM: if no chunks, this is the easiest way to inject css into one js file
        manualChunks(id) {
          if (id.includes('components')) {
            // Extract the file name without extension
            const componentName = path.basename(id).split('.')[0];
            return `components/${componentName}`;
          }
          return 'utils';
        },
        entryFileNames: `[name].js`,
        chunkFileNames: `[name].js`,
        assetFileNames: `[name].[ext]`,
        globals: {
          vue: 'Vue',
        },
      },
    },
  },
});

and this is file with those js imports:

import "./HelloWorld.js";
import "./Test.js";
const a = (t) => t.slice(0, 1).toUpperCase() + t.slice(1), i = (t, o) => {
  const e = t.__vccOpts || t;
  for (const [c, r] of o)
    e[c] = r;
  return e;
};
export {
  i as _,
  a as c
};

When manually removing those imports from dist folder, my consuming package can render correctly, otherwise it fails with hmr.ts:204 ReferenceError: Cannot access 'n' before initialization at HelloWorld.js:16:25

Here is also compiled HelloWorld:

import "/@fs/Users/srdjan.medjo/SrleProjects/uar/vtrips.ownerportalfe/packages/shared/dist/assets/HelloWorld.css?t=1707381720026";
import { defineComponent as r, ref as l, openBlock as a, createElementBlock as c, createElementVNode as e, toDisplayString as o } from "/node_modules/.vite/deps/vue.js?v=b631ae9a";
import { _ as n } from "/@fs/Users/srdjan.medjo/SrleProjects/uar/vtrips.ownerportalfe/packages/shared/dist/assets/utils.js?t=1707381720026";
const _ = { class: "h1" }, d = { class: "color" }, m = /* @__PURE__ */ r({
  __name: "HelloWorld",
  props: {
    msg: { default: "default msg value" }
  },
  setup(p) {
    const t = l(34);
    return (s, i) => (a(), c("div", null, [
      e("h1", _, "This is from shared " + o(t.value), 1),
      e("div", d, o(s.msg), 1)
    ]));
  }
}), v = /* @__PURE__ */ n(m, [["__scopeId", "data-v-b1d33612"]]);
export {
  v as default
};

Any ideas on how to approach this?

when i use input to set entries and change css name in manualChunks, inject failed

when i use input to set entries and change css name in manualChunks, inject failed. and got:
/* empty css */

manualChunks cchange source.css: index*.css to XxxComponent.css

this failed:

input: {
  'index':'ui/index.ts'
},
output: {
  manualChunks: (id) => {
              if (id.includes('.css'))
               return pipe(
                  split('/'),
                  last,
                  split('.css'),
                  head
                )(id) as string
  }
  entryFileNames: (chunkInfo) => chunkInfo.name === 'index' ? '[format]/index.js' : '[format]/[name]/index.js',
  chunkFileNames: '[format]/[name]/index.js',
  assetFileNames: '[ext]/[name].[ext]',
}

this worked:

input: {
  'index':'ui/index.ts'
},
output: {
  manualChunks: (id) => {
    //           if (id.includes('.css'))
    //             return pipe(
    //               split('/'),
  //                 last,
     //              split('.css'),
   //                head
 //               )(id) as string
  }
  entryFileNames: (chunkInfo) => chunkInfo.name === 'index' ? '[format]/index.js' : '[format]/[name]/index.js',
  chunkFileNames: '[format]/[name]/index.js',
  assetFileNames: '[ext]/[name].[ext]',
}

CSS file imports are appearing above banner section

Hi
So I'm using this library in building a React library that is supposed to work in Next.js.
As you know in Next.js 13+, you need to have a "use client"; directive at the top of each component file.

This is usually achieved in vite by adding the "use client"; directive as a banner.
But this library puts the css imports at the top of the file, so the directives are not working.

Is there a way to make the css imports appear after the banner?
Or should I be tackling this issue using something other than banners completely??

Thanks for your help.

Replace `renderChunk` with `generateBundle` hook might be better? (vite:lib-inject-css)

您好,在使用的时候遇到了这个问题,如果是放在 renderChunk 中的话,同一个 vue 文件在这个 hook 中可能对应有2个 chunk (搜了一圈不知道为啥),如图所示
在 OmegaDialog.vue2.mjs 这个 chunk 里面是有 importedCss & chunk.viteMetadata 的,另一个 chunk 是没有的,最终 build 完成 OmegaDialog.vue2.mjs 这个 chunk 却没有 emit 相应的文件出来

image

image

似乎把相应的逻辑写在 generateBundle 也可以,(这时候就只会一个 chunk 了):

    generateBundle(options, bundle) {
      Object.entries(bundle).forEach(([fileName, chunk]) => {
        // @ts-ignore
        if (!chunk.viteMetadata || chunk.type === "asset") return;
        const { importedCss } = (chunk as OutputChunk).viteMetadata!;
        if (!importedCss.size) return;

        const code = chunk.code;
        const ms = new MagicString(code);
        for (const cssFileName of importedCss) {
          let cssFilePath = path.relative(
            path.dirname(chunk.fileName),
            cssFileName
          );

          cssFilePath = cssFilePath.startsWith(".")
            ? cssFilePath
            : `./${cssFilePath}`;
          ms.prepend(`import '${cssFilePath}';\n`);
        }
        chunk.code = ms.toString();
        chunk.map = ms.generateMap();
      });
    }

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.