Giter Club home page Giter Club logo

nuxt-custom-elements's Introduction

share me:

nuxt-custom-elements

Nuxt Custom-Elements

Grabarz & Partner - Module

main develop Sonarcloud Status

npm version npm downloads

Renovate - Status License

Publish your Components as a vue-custom-element standalone build.

Nuxt Custom-Elements allows you to export your existing project components as custom elements for integration into external pages.

Features

  • Using modern and client build
  • Export components as widgets
  • Use the Shadow DOM 🥷
  • Use TailwindCSS and Vuetify for your widgets

📖   Learn more in the documentation

Browsers support

For cross-browser compatibility (IE11+) the client build uses the Polyfill custom-elements

Polyfill not included in the modern build, optional include by option modernPolyfill (Learn more).

Development

  1. Clone this repository
  2. Install dependencies using npm install or yarn install
  3. Start development server using npm run dev or yarn dev

Preview

  1. Clone this repository
  2. Install dependencies using yarn install or npm install
  3. Build and start with express yarn start:build or npm run start:build
  4. Open endpoints via http://127.0.0.1:3000/ in Browser

License

MIT License

nuxt-custom-elements's People

Contributors

dependabot[bot] avatar markuzzi avatar renovate-bot avatar renovate[bot] avatar semantic-release-bot avatar thornwalli 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

nuxt-custom-elements's Issues

Export

Hello,

I like the idea of this module. Currently, I export some parts of our page with @vue/cli as WebComponent for some of our partners. However, this is not an ideal solution. I need to maintain two separated configs. Nuxt and vue cli. Now I thought I could replace the vue cli approach with this module. But the thing is, currently I don't see any way to export the generated files. I mean yes, it generates the javascript files in .nuxt. However, it is hard to export them from there.

I think this module should have some way to generate some kind of bundle in a specific folder. One important thing would be that it has a predictable entry file. The current generated entry file looks like this: name.somehash.js which is not really workflow friendly. I expect an easy way to export the bundle to upload it later to a CDN for example.

Generate only a single lang?

I use nuxt-i18n in my project and when I generate my final component.js every lang file of any language is in the resulting js file. I would like to split it, so that I have different js for different languages. Example component-en.js , component-de.js. Is this possible and how?

options.props not considered for HTML tag if options is a function

Describe the bug
I use nuxt-custom-elements to generate a ce within a shadow dom (shadow: true).
To instantiate the shadow root, I have to add the hook beforeCreateVueInstance which is only recognized if tag options are given as a function. Otherwise, the JSON.stringify ignores the function.

However, if options are given as function, the HTML entry in the test index.html is not generated with default props, since the function getTagHTMLFromEntry does not evaluate the functin.

Afaik, the solution would be to change the getTagHTMLFromEntry function's first line to
const options = typeof tag.options === 'function' ? tag.options() : (tag.options || {});

In my tests, everything works fine.

Generating components with baked-in async `data`

Is it possible to generate components with async data that is baked in? For a somewhat contrived example, I'd have a <FavoriteDog /> component built out as a template like:

<template>
  <h1>{{ dogName }}</h1>
</template>
<script>
export default {
  data () {
    return {
      dogName: null
    };
  },
};
</script>
<style scoped>
h1 { color: red }
</style>

And ideally, I'd want to have a bunch of web components output per dog name, like: <dog-spot></dog-spot>, <dog-fido></dog-fido>

Of course in the example above, realistically it would be a large amount of JSON data from an API that someone using your components wouldn't have access to, and it wouldn't be nearly as simple as just inputting a name via a web component prop when they use it like <dog name="fido"></dog>.

The props option unfortunately only outputs the data into the (nuxt) generated HTML template, so I'm not able to expect people using my components to pass in this massive JSON payload every time they use my component. I read about using the fetch() hook in Nuxt.js, but that unfortunately doesn't seem to do the trick with your plugin (e.g.,

<!-- ... -->

<script>
export default {
  // ...
  async fetch() {
    const dogs = await this.$axios.$get(`https://api.nuxtjs.dev/dogs`)

    const dogOne = dogs[0]

    this.dogName = dogOne.name;

  },
  fetchOnServer: true,
  // ...
};

Strange behavior with multiple external applications

Hello, I would like help with a strange behavior that is happening in an application.

The main application makes use of 2 web components, each of which comes from external applications. The external applications are "academic services" and "messages".

When I access the page in the main application, which will load the web component of the "academic services" application, everything works perfectly. See the print of the loaded scripts:

image

So when I navigate to the "messages" page, the scripts seems to be partially loaded and I get this error in the console:

image

image

Notice that only chunk "5" was loaded. Now, if I reload this page, all chunks are loaded and everything works perfectly:

image

I tested several configurations (use of hashes in chunks, disabled polyfill, etc.) but nothing seems to work. The impression is that it is reusing previously downloaded chunks (As it only downloaded chunk 5. After the refresh, all chunks are downloaded).

This is the "academic services" configuration:

customElements: {
  buildDir : 'dist/web-components',
  entries  : [
    {
      name: 'default',
      webpackExtend(config) {
        config.output = {
          ...config.output,
          publicPath    : 'publicPathPlaceholder',
          filename      : `[name].academic-services.js`,
          chunkFilename : '[name].[hash].js'
        };

        config.plugins = [
          ...config.plugins,
          new (require('webpack-dynamic-public-path'))({
            externalPublicPath: `window.acedemicServicesCustomPublicPath`
          })
        ];
      },
      tags: [
        {
          name  : 'WcMainAs',
          path  : '@/entries/default/main-as',
          async : true,
          options() {
            return {
              props          : ['token'],
              destroyTimeout : null,
              vueInstanceCreatedCallback() {
                window.dispatchEvent(new CustomEvent('wcVueInstanceCreated'));
              }
            };
          }
        }
      ]
    }
  ]
}

And this one is from "messages":

customElements: {
  buildDir : 'dist/web-components',
  entries  : [
    {
      name: 'default',
      webpackExtend(config) {
        config.output = {
          ...config.output,
          publicPath    : 'publicPathPlaceholder',
          filename      : `[name].messages.js`,
          chunkFilename : '[name].[hash].js'
        };

        config.plugins = [
          ...config.plugins,
          new (require('webpack-dynamic-public-path'))({
            externalPublicPath: `window.messagesCustomPublicPath`
          })
        ];
      },
      tags: [
        {
          name  : 'WcMainMs',
          path  : '@/entries/default/mainMs',
          async : true,
          options() {
            return {
              props          : ['token'],
              destroyTimeout : null,
              vueInstanceCreatedCallback() {
                window.dispatchEvent(new CustomEvent('wcVueInstanceCreated'));
              }
            };
          }
        }
      ]
    }
  ]
}

Any suggestion is welcome, and thanks again 😄

Example of using a component from another origin

Is your feature request related to a problem? Please describe.
I want to be able to include components created from another project, which is hosted on a different origin. The examples only include using components from the same project.

Describe the solution you'd like
I think the IFrames are used to demonstrate that a component has come from elsewhere, however I'd like to see an example with components used from a different origin.

Describe alternatives you've considered
I have adapted the example this way and it appears to work but I am unsure if I am doing it correctly:

<template>
  <div>
    <client-only>
        <custom-component />
    </client-only>
  </div>
</template>

<script>
import Vue from 'vue';

Vue.config.ignoredElements = [
  'custom-component'
];

export default {
  data () {
    return {
      isDev: process.env.NODE_ENV === 'development',
      base: 'https://another-domain.org/'
    };
  },

  head () {
    const script = [];
    if (!this.isDev) {
      script.push({
        type: 'text/javascript',
        innerHTML: `window.customPublicPath = '${this.base}nuxt-custom-elements/custom-component/';`,
        body: true
      }, {
        type: 'text/javascript',
        src: `${this.base}nuxt-custom-elements/custom-component/custom-component.js`,
        async: true,
        defer: true,
        body: true
      });
    }
    return {
      script,
      __dangerouslyDisableSanitizers: ['script']
    };
  },
  created () {
    this.isDev && this.$registerCustomElementsEntry('CustomComponent');
  }
};
</script>

Cheers 💯

webpackChunkName for Polyfill

return await import('document-register-element/build/document-register-element'); // For cross-browser compatibility (IE9+) use Custom Elements polyfill.

The result of this line when webpack chunking is enabled is a file output of 1.js. It should have a chunkname /* webpackChunkName: "document-register-element" */ defined. Even then it would be better if there was a way to tell the build to not chunk this file and include it in our entry point.

switching between multiple embedded components seems buggy

Describe the bug
I have a few nuxt-custom-elements components embedded in my website (https://t3chflicks.org/Services) which are loaded from an external source (document-store.t3chflicks.org, medium-to-markdown.t3chflicks.org). When I switch page, loading a diferrent nuxt-custom-elements component, there seems to be odd behaviour:

  • reloading the same component instead of new one
  • failing to load with an error of
    Uncaught TypeError: Illegal constructor
     at new n (viewer-component.js:432)
    

To Reproduce
Steps to reproduce the behavior:

Sorry if this isnt enough informatio, please say if you would like an example project.

Cheers

[Help] Fonts are not loaded correctly

We are creating some web components using this awesome lib.

But I'm stuck in a problem...

It looks like the fonts are not properly loaded when generating the component build.

What i've tried so far:

Load fonts in entry
image

This not work. When I include the generated bundle into HTML pages, an error appears in network
image

How can we add font files to generated bundle?

Any suggestion is welcome

How to use the styles in vue files

There is the following info in the README:

⚠️  Important: CSS from the SingleFile (.vue) cannot be used, this will be included by the vue-loader by using the style-loader.

If it's not supported, what's the workaround? For reference, we have around 40 components that you these inline CSS in Vue and we would like to avoid duplication.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

A way to use with Vuetify ?

Hi, i'm working on Nuxt App combined with Vuetify and i'd wish to build a Widget usable for external websites which reuse already existing components in Nuxt App.
But i don't understand how to implement ....
I've got errors when i tried with build version
"this.$vuetify is undefined"
"TypeError: Cannot read property 'theme' of undefined"

My work look like this for now (components/widgets/widget.vue)

<template>
  <div id="widget" @click.prevent.stop>
      <v-card
        color="#385F73"
        flat
        width="50"
        height="200"
        @click="dialog=true"
      >
        Click Here
      </v-card>
  <v-dialog
    v-model="dialog"
    max-width="1200"
  >
    <v-card color="white" id="modalWidget">
      Dialog content
    </v-card>

  </v-dialog>
  </div>
</template>

<script>

import Vuetify, { VCard, VDialog } from 'vuetify/lib'

export default {
  // props: ['title'],
  data () {
    return {
      activeTab: '',
      dialog: false,
    }
  },
  components: {
    VCard,
    VDialog
  },
</script>

<style lang="scss">
  #widget {
    .v-card {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
  }
</style>

It works fine in dev mode with

this.$registerCustomElementsEntry('Widget')

and custom element in template layout but not with build command.

Thanks for reading

Not working with extractCSS

Describe the bug
When i turned on extractCSS, this module is not working

/nuxt-custom-elements-example-main/node_modules/extract-css-chunks-webpack-plugin/dist/index.js:70
    const resource = this._identifier.split('!').pop();

To Reproduce
Steps to reproduce the behavior:
extractCSS: true

Expected behavior
Need support extractCSS to generate css file

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Using npm packages for Renovate presets is now deprecated. Please migrate to repository-based presets instead.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/beta.yml
  • actions/setup-node v4
  • actions/checkout v4
  • actions/cache v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/cache v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/cache v4
  • actions/upload-artifact v4
  • actions/download-artifact v4
  • peaceiris/actions-gh-pages v3
.github/workflows/codeql-analysis.yml
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • github/codeql-action v3
  • github/codeql-action v3
  • github/codeql-action v3
.github/workflows/main.yml
  • actions/setup-node v4
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/cache v4
  • actions/setup-node v4
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
.github/workflows/sonar-cloud.yml
  • actions/setup-node v4
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/cache v4
.github/workflows/test.yml
  • actions/setup-node v4
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/cache v4
npm
package.json
  • @unplugin-vue-ce/sub-style 1.0.0-beta.19
  • change-case 5.4.3
  • clone 2.1.2
  • defu 6.1.4
  • html-webpack-plugin 5.6.0
  • lodash-es 4.17.21
  • vue-web-component-wrapper 1.4.0
  • webpack-bundle-analyzer 4.10.1
  • @babel/eslint-parser 7.23.10
  • @commitlint/cli 19.0.3
  • @commitlint/config-conventional 19.0.3
  • @nuxt/module-builder 0.5.5
  • @nuxt/webpack-builder 3.10.3
  • @nuxtjs/eslint-config 12.0.0
  • @nuxtjs/eslint-config-typescript 12.1.0
  • @types/node 20.11.24
  • commitlint 19.0.3
  • eslint-config-prettier 9.1.0
  • eslint-formatter-json-relative 0.1.0
  • eslint-plugin-jsonc 2.13.0
  • eslint-plugin-no-unsanitized 4.0.2
  • eslint-plugin-prettier 5.1.3
  • eslint-plugin-security 2.1.1
  • eslint-plugin-sonarjs 0.24.0
  • eslint-plugin-xss 0.1.12
  • finalhandler 1.2.0
  • get-port-please 3.1.2
  • husky 9.0.11
  • lint-staged 15.2.2
  • markdown-it-inline-comments 1.0.1
  • nuxt 3.10.3
  • playwright 1.42.1
  • postcss-html 1.6.0
  • postcss-preset-env 9.4.0
  • prettier 3.2.5
  • read-pkg 9.0.1
  • serve-static 1.15.0
  • standard-version 9.5.0
  • stylelint 16.2.1
  • stylelint-config-recess-order 4.6.0
  • stylelint-config-standard 36.0.0
  • vitepress 1.0.0-rc.44
  • vitest 1.3.1
nvm
.nvmrc
  • node v20.10.0

  • Check this box to trigger a request for Renovate to run again on this repository

[Ask] How to change the webpack module default rules

Hello,

I'm trying to add an prefix to Vuetify classes due to global scope conflict, as mentioned in this comment

But I'm not sure how to access and manipulate those rules. I believe the webpackExtend method doesn't expose everything that would be needed in this case.

Also, i'm trying to make use of webpack-chain to get the result I want, but I'm not sure if this is the way.

Any suggestion is welcome

[Ask] Multiple entry points share same application

Hi,

We are developing an application that needs 2 entry points, let's call them A and B.

I believe this is a limitation of Nuxt, but if I instantiate custom plugin at entry point A, the same plugin is available at entry point B.

This can be a limiting factor, as we try to create an architecture where each entry point would load its own plugins, stores, translations, and so on.

This only happens if the application itself uses the entry point, eg: this.$customElements.registerEntry('A');.

After generating the build, consuming externally through the URL http://validhostname.com/nuxt-custom-elements/A/A.js, it works correctly.

Thank you in advance ;)

webpackConfigs.flat is not a function

Hey!

Thanks for making this plugin! I'm having some trouble using it though. I'm on Nuxt 2.12.2 and Typescript 3.8.3.

My nuxt-config
['nuxt-custom-elements', {
  analyzer: true,
  polyfill: true,
  staticPath: '@/static',
  entries: [
    {
      name: 'CoopHandla',
      tags: [
        {
          name: 'CustomElementGrid',
          path: '@/components/apps/Handla',
          options: {
            props: {
              placement: {
                type: String,
                required: true
              },
              placementMore: {
                type: String,
                required: false,
                default: undefined
              },
              rows: {
                type: Number,
                default: 3
              },
            },
          }
        }
      ]
    },
  ],
}],

When I'm running nuxt generate I get the following error: TypeError: webpackConfigs.flat is not a function which leads me to the following line:

const builds = parallelBuild(webpackConfigs.flat(), parallelBuilds)

I'm not really sure where to go from here. I've added es2019.array to my tsconfig to rule out that was missing. Any suggestions? Cheers

Usage with @nuxt/components

When I have an auto imported component in my bundle, I get an error installComponents is not defined.
Turning off auto import, and manually bringing the component in, things work fine.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Cannot set properties of undefined (setting 'shadowMode') at setLoaderRulesForShadowMode

Describe the bug
When compiling my component, I get the following error:

 FATAL  Cannot set properties of undefined (setting 'shadowMode')
  at setLoaderRulesForShadowMode (node_modules/nuxt-custom-elements/utils/webpack.js:54:38)
  at getWebpackConfig (node_modules/nuxt-custom-elements/utils/webpack.js:98:13)
  at node_modules/nuxt-custom-elements/utils/webpack.js:262:22
  at Array.map (<anonymous>)
  at node_modules/nuxt-custom-elements/utils/webpack.js:262:8
  at Array.map (<anonymous>)
  at prepareConfigs (node_modules/nuxt-custom-elements/utils/webpack.js:260:49)
  at node_modules/nuxt-custom-elements/module.js:58:29
  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  at async Nuxt.callHook (node_modules/hable/dist/hable.js:1:959)
  at async Builder.build (node_modules/@nuxt/builder/dist/builder.js:333:5)
  at async ensureBuild (node_modules/@nuxt/cli/dist/cli-generate.js:145:3)
  at async Object.run (node_modules/@nuxt/cli/dist/cli-generate.js:283:7)
  at async NuxtCommand.run (node_modules/@nuxt/cli/dist/cli-index.js:413:7)

console.log(vueLoaderRule) after line 51 gives this:

{
  test: /\.vue$/i,
  use: [
    {
      loader: '/path/to/project/node_modules/@nuxt/components/dist/loader.js',
      options: [Object]
    },
    {
      loader: '/path/to/project/node_modules/vue-loader/lib/index.js',
      options: [Object]
    }
  ]
}

I was able to fix it by changing vueLoaderRule.options.shadowMode = true; at line 54 to vueLoaderRule.use.find((temp)=>temp.loader.includes('/node_modules/vue-loader/')).options.shadowMode = true;

Additional context

  • I'm currently on v1.9.1
  • I saw that a similar fix is already on the beta branch (vueLoaderRule.use[0].options.shadowMode = true;), but that didn't work, because vue-loader was at index 1 and not 0

webpack chunk optimization

Is your feature request related to a problem? Please describe.
The bundles I create with nuxt-custom-elements grew over time, especially because of large libraries like vuetify.
Thus, I want to optimize bundling and create chunks with webpack.
This can be achieved with the async flag, however, this only creates chunks for the components, not for the libs.

Describe the solution you'd like
I want to be able to configure webpack optimization.

Solution
I added another option called "webpackOptimization", e.g.

webpackOptimization: {
    splitChunks: {
      automaticNameDelimiter: '-',
      minChunks: 1,
      minSize: 100_000,
      chunks: 'all',
      cacheGroups: {
        vuetify: {
          test: /vuetify/,
          name: 'ui-framework',
          chunks: 'all',
          priority: 10,
          enforce: true
        },
      },
    }
  }

To make this happen, utils/webpack.js has to be adapted in lines 88:91

    optimization: Object.assign({
      // minimize: false,
      runtimeChunk: false
    }, options.webpackOptimization),

Also, to have meaningful names for chunks if the async flag is used for tags, templ/entry.js line 26 should be changed to

 %><%= `Vue.customElement('${name}', () => { return import(/* webpackChunkName: "${name}" */ '${path}').then(module => (typeof module.default === 'function' ? (new module.default).$options : module.default) ); }, ${options});\n` %><%

Would that be a valuable extension to you great module?

Thanks!

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

How to use nuxt-i18n

I am sharing components with nuxtjs, which use nuxt-i18n. Is there a way to use {{ $t('translation') }} in custom element?

[Progress] `nuxt@3` support

⚠️ Currently, there is no backward compatibility with nuxt@2 oder bridge when updating.

Nuxt 3 version is available 🎉

Install

npm i nuxt-custom-elements@beta

Todos

Features

Problems?

nuxt3 - custom element entry with multiple tags only uses first tag

Describe the bug
If a custom element entry point has more than one tag object only the first will be used.

To Reproduce
So if you have a nuxt.config.ts that looks like

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  ssr: false,
  target: 'static',
  devServer: {
    port: 4321,
  },
  modules: [
    '@vueuse/nuxt',
    '@pinia/nuxt',
    '@nuxtjs/tailwindcss',
    'nuxt-custom-elements',
  ],
  customElements: {
    entries: [
      {
        name: 'CustomComponents',
        tags: [
          {
            name: 'Example',
            path: '@/components/Example.ce',
            options: {
              props: {
                heading: 'Example Nuxt Config Prop Title',
              },
            },
            slotContent: 'Hello Example from the Nuxt Config!',
          },
          {
            name: 'Tester',
            path: '@/components/Tester.ce',
            options: {
              props: {
                copy: 'Tester copy from Nuxt config',
              },
            },
          },
        ],
      },
   ],
 },
});

And your two components that are to be built as web components
Example.ce.vue

<script lang="ts" setup>
import 'tailwindcss/tailwind.css';

export interface Props {
  heading?: string
}

withDefaults(defineProps<Props>(), {
  heading: 'Default example heading',
});

const { x, y } = useMouse();
</script>

<template>
  <div class="text-white bg-zinc-700 flex flex-col p-4 rounded-lg">
    <h1 class="italic">
      {{ heading }}
    </h1>
    <p>Mouse coordinates: {{ x }}, {{ y }}</p>
    <div class="text-zinc-200">
      <slot>Default example content</slot>
    </div>
  </div>
</template>

<style lang="postcss">
@tailwind base;
@tailwind components;
@tailwind utilities;
</style>

Tester.ce.vue

<script lang="ts" setup>
import 'tailwindcss/tailwind.css';

export interface Props {
  copy?: string
}

withDefaults(defineProps<Props>(), {
  copy: 'Default tester copy',
});

const { x, y } = useMouse();
</script>

<template>
  <div class="text-white bg-red-700 flex flex-col p-4 rounded-lg">
    <h1 class="italic">Tester component</h1>
    <h2>Mouse coordinates: {{ x }}, {{ y }}</h2>
    <p class="text-gray-300">
      {{ copy }}
    </p>
  </div>
</template>

<style lang="postcss">
@tailwind base;
@tailwind components;
@tailwind utilities;
</style>

After running nuxt generate you can serve the provided HTML file with

npm i -g serve # if you don't already have this installed
serve dist/nuxt-custom-elements/custom-components

Expected behavior
Both web components would render correctly rather than the first in the nuxtConfig.customElements.entries[0].tags array.

Screenshots
See here #433 (comment)

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.