vue-splide only works in Nuxt dev environment - javascript

I am having issues trying to make vue-splide work outside of nuxt dev, after generating the static or the spa, it doesn't work properly.
Changing the target in nuxt.config.js from static to SPA doesn't solve the problem.
Instead of using nuxt generate I also tried nuxt build and the results are the same.
The two pictures are here:
The slider is working only in one of them, as it can be seen.
Any help on making it work properly so I can deploy the site?
nuxt.config.js
export default {
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'Visgrow Internships',
htmlAttrs: {
lang: 'en',
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'preconnect', href: 'https://fonts.gstatic.com' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css2?family=Roboto:ital,wght#0,500;1,300;2,100&display=swap' },
],
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [{ src: '~/plugins/splide.client.js', ssr: false }],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/typescript
'#nuxt/typescript-build',
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
'#nuxtjs/axios'
],
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
}
splide.client.js
import Vue from 'vue';
import VueSplide from '#splidejs/vue-splide';
// import '#splidejs/splide/dist/css/splide.min.css';
// Importing the original CSS does not change a thing. Also, I import the above CSS in the bellow css
import '../plugins-css/splide.css';
Vue.use(VueSplide);
new Vue({
el: '#app',
render: h => h(App),
});

Tried it on my side, working perfectly fine.
Install the package with either yarn or npm.
yarn add #splidejs/vue-splide
Setup the plugin in the usual way.
vue-splide.client.js
import VueSplide from '#splidejs/vue-splide'
import Vue from 'vue'
import '#splidejs/splide/dist/css/themes/splide-sea-green.min.css'
Vue.use(VueSplide)
Import the plugin in plugins, no need to use ssr: false (it actually does not exist anymore) nor mode since you went to suffix the file with client.js.
export default {
ssr: false,
target: 'static',
plugins: ['~/plugins/vue-splide.client.js'],
...
}
Then, using it in a view is perfectly fine, styling aside.
pages/index.vue
<template>
<div>
<splide class="custom">
<splide-slide>
<img src="https://source.unsplash.com/weekly?water" />
</splide-slide>
<splide-slide>
<img src="https://source.unsplash.com/weekly?fire" />
</splide-slide>
<splide-slide>
<img src="https://source.unsplash.com/weekly?earth" />
</splide-slide>
</splide>
</div>
</template>
<style scoped>
.splide__slide {
height: 50vh;
margin: 0 auto;
}
.custom {
height: 50vh;
width: auto;
}
</style>
For the project, I went with ssr: false and target: 'static' (PS: target: SPA does not exist) so, I then need to do
yarn generate
yarn start
And here is the result

Related

CSS import not working in .storybook/preview.js after adding 'storybook-addon-next',

Hi I am using Storybook 6.4.22 with Next 12.1.5 and Typescript 4.4.2(Node 16). I have to add global fonts for our stories. I tried adding that in preview.js and it worked fine initially. I had to use 'storybook-addon-next' because some of our components are pulling info out of configs(getConfig()?.serverRuntimeConfig?.config). After adding the addon my global import of fonts has stopped working.
Thanks in advance for your help.
storybook/Main.js
module.exports = {
stories: ['../src//*.stories.mdx', '../src//*.stories.#(js|jsx|ts|tsx)'],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/addon-interactions',
'storybook-addon-tags',
'storybook-addon-next',
],
framework: '#storybook/react',
core: {
builder: '#storybook/builder-webpack5',
},
}
storybook/preview.js
import '#UI/palette/build/web/fonts/fonts-cdn.css' //css import
export const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
}

Is it possible to make a library of Vue highcharts components?

I am just desperate for an answer but there's a hope to find the answer here.
I Used following stuff:
"vite": "^2.7.13",
"highcharts": "^9.3.3",
"highcharts-vue": "^1.4.0"
I would like to make a library of vue components including highcharts charts. I tried to make BarChart with rollup config like this:
import vue from "rollup-plugin-vue";
import typescript from "rollup-plugin-typescript2";
import resolve from "rollup-plugin-node-resolve";
import postcss from "rollup-plugin-postcss";
import dts from "rollup-plugin-dts";
import cleaner from "rollup-plugin-cleaner";
import commonjs from "#rollup/plugin-commonjs";
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import image from '#rollup/plugin-image';
const plugins = [
resolve(),
typescript({
check: false,
useTsconfigDeclarationDir: true,
}),
vue({
preprocessStyles: true,
css: false,
template: {
isProduction: true,
},
}),
peerDepsExternal(),
commonjs(),
postcss({
extensions: [".css"],
}),
image(),
];
const AppChart = [
{
input: "./demo-v3/src/components/Chart.vue",
output: [
{
format: "esm",
file: "./demo-v3/lib/UI/AppChart/index.js",
},
],
external: ["#vue"],
plugins: [...plugins, commonjs({
namedExports: {
"node_modules/highcharts-vue/dist/highcharts-vue.min.js": ["Chart"],
},
}),],
},
];
const config = [...AppChart];
export default config;
My component BarChart.vue looks like this:
<template>
<div class="chart-wrapper">
<Chart :chart-options="lineChartOptions" />
</div>
</template>
<script setup lang="ts">
import Chart from "./CommonChart.vue";
const props = defineProps({
chartData: {
type: Object,
// eslint-disable-next-line #typescript-eslint/no-empty-function
default: () => {},
},
});
const exportingOptions = () => {
return {
buttons: {
contextButton: {
menuItems: [
"viewFullscreen",
"separator",
"downloadPNG",
"downloadPDF",
"printChart",
"separator",
"downloadCSV",
"downloadXLS",
],
},
},
};
};
let lineChartOptions = {
...props.chartData,
exporting: exportingOptions(),
credits: { enabled: false },
};
</script>
<style lang="scss">
.chart-wrapper {
padding: 15px;
width: 1140px;
height: 440px;
border: 1px solid #c4c4c4;
}
</style>
And there is a common chart component looks like this:
<template>
<highcharts class="hc" :options="chartOptions" />
</template>
<script setup lang="ts">
import { Chart as highcharts } from "highcharts-vue";
import Highcharts from "highcharts";
const props = defineProps({
chartOptions: {
type: Object,
// eslint-disable-next-line #typescript-eslint/no-empty-function
default: () => {},
},
});
</script>
It works when I use BarChart and doesn't work after bundling with rollup.
What can I do wrong?
my colleague found this guide with the setup which is worked for me.
I leave it here for who can't find the same:
https://dev.to/shubhadip/vue-3-component-library-270p
UPDATED:
https://devsday.ru/blog/details/73660 - vite can build lib out-of-box. I haven't tried this way but suspect it works well. As always, I should look throw documentation carefully

Rollup imported css in a webcomponent

I am creating simple webcomponent now I want to import css , I found a method using adpotedstylesheet.
Here is how I import it my webcomponet
import sheet from './styles/swal.css' assert { type: 'css' };
class Demo extends HTMLElement{
constructor() {
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(Demo.content.cloneNode(true));
document.adoptedStyleSheets = [sheet];
this.shadowRoot.adoptedStyleSheets = [sheet];
}
}
window.customElements.define("demo-component", Demo);
and here is my rollup settup for bundling my component
import summary from "rollup-plugin-summary";
import { terser } from "rollup-plugin-terser";
import resolve from "#rollup/plugin-node-resolve";
import replace from "#rollup/plugin-replace";
import postcss from "rollup-plugin-postcss";
import { eslint } from "rollup-plugin-eslint";
import babel from "rollup-plugin-babel";
import { uglify } from "rollup-plugin-uglify";
import commonjs from 'rollup-plugin-commonjs';
export default {
input: "index.js",
output: {
file: "dist/index.js",
format: "esm",
},
onwarn(warning) {
if (warning.code !== "THIS_IS_UNDEFINED") {
console.error(`(!) ${warning.message}`);
}
},
plugins: [
postcss({
plugins: [],
extensions: [".css"],
}),
resolve({
jsnext: true,
main: true,
browser: true,
}),
commonjs(),
eslint({
exclude: ["src/styles/**"],
}),
babel({
exclude: "node_modules/**",
}),
terser({
ecma: 2017,
module: true,
warnings: true,
mangle: {
properties: {
regex: /^__/,
},
},
}),
summary(),
replace({
"Reflect.decorate": "undefined",
preventAssignment: true,
ENV: JSON.stringify(process.env.NODE_ENV || "development"),
}),
process.env.NODE_ENV === "production" && uglify(),
],
};
Now when i run npm run buil I get the following error.
[!] (plugin commonjs) SyntaxError: Unexpected token (3:38)`
What am I doing wrong here ???
Currenly, Rollup doesn't support import assertions. There is open issue for Rollup to address it. There is an experimental Rollup plugin that supports this but it seems to have some issues.
Another option you can try is to use rollup-string-plugin. You can use it to read CSS file as a string and then build your constructible stylesheets and assign it to adoptedStyleSheets property as explained here for Webpack. Following is one example of doing it..
// Read SCSS file as a raw CSS text
import styleText from './my-component.css';
const sheet = new CSSStyleSheet();
sheet.replaceSync(styleText);
// Custom Web component
class FancyComponent1 extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
// Attaching the style sheet to the Shadow DOM of this component
shadowRoot.adoptedStyleSheets = [sheet];
shadowRoot.innerHTML = `
<div>
<p>Hello World</p>
</div>
`;
}
}
Side note: With Webpack, you can use raw-loader.
Be aware that adoptedStyleSheets is currently not supported by Safari on Mac and iOS. But, Rollup might handle this for you - I don't know.
Another solution is to check out:
https://www.npmjs.com/package/csshtml-module
This CLI tool can be set up to let you automatically compile CSS/HTML to native JS modules.
I created that CLI tool to tackle this issue. It might not be for everyone - but maybe it resonate with you.

Rollup + React 17 with new JSX Transform - "React is not defined"

I'm trying to prototype a microfrontend architecture with Rollup and a couple of create-react-app applications. However when I locally yarn link my external app with the container app, I run into the following error:
ReferenceError: React is not defined
23500 | return /#PURE/React.createElement("div", {
| ^ 23501 | id: "container",
23502 | className: "flex flex-col h-screen"
23503 | }, /#PURE/React.createElement(BrowserRouter, null, /#PURE/React.createElement(Header, {
I think it's because we're not importing React at the top of every component/file because of React 17's new JSX Transform allowing you to not have to do that. I'd really like to be able to build our micro frontend package without having to import React in every file, is there a way to do this?
Here is the rollup.config.js:
import babel from 'rollup-plugin-babel';
import commonjs from '#rollup/plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import postcss from 'rollup-plugin-postcss';
import resolve from '#rollup/plugin-node-resolve';
import image from '#rollup/plugin-image';
import visualizer from 'rollup-plugin-visualizer';
import includePaths from 'rollup-plugin-includepaths';
import replace from '#rollup/plugin-replace';
import pkg from './package.json';
const extensions = ['.js', '.jsx', '.ts', '.tsx'];
export default {
input: './src/App.jsx',
output: [
{
file: pkg.main,
format: 'cjs',
},
{
file: pkg.module,
format: 'esm',
},
],
plugins: [
external(),
postcss(),
resolve({
mainFields: ['module', 'main', 'jsnext:main', 'browser'],
extensions,
}),
image(),
visualizer(),
includePaths({ paths: ['./'] }),
replace({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
babel({
exclude: 'node_modules/**',
plugins: [
[
'module-resolver',
{
root: ['src'],
},
],
],
presets: ['#babel/preset-react'],
}),
commonjs(),
],
};
In tsconfig.json, add the following code
{
"compilerOptions": {
"jsx": "react-jsx",
}
}
Fixed this by adding { runtime: "automatic" } to the #babel/preset-react preset.
From the preset-react runtime docs:
automatic auto imports the functions that JSX transpiles to. classic does not automatic import anything.
Also mentioned in the React post about the new JSX transform:
Currently, the old transform {"runtime": "classic"} is the default option. To enable the new transform, you can pass {"runtime": "automatic"} as an option to #babel/plugin-transform-react-jsx or #babel/preset-react
Here's a sample:
{
// ...
plugins: [
// ...
babel({
// ...
presets: [
// ...
["#babel/preset-react", { runtime: "automatic" }],
]
})
]
}

Implementing Stripe on Nuxt App - StripeCheckout not found in 'vue-stripe-checkout'

I'm trying to implement stripe on my NuxtJS App but I'm facing this error :
StripeCheckout not found in 'vue-stripe-checkout'.
I was trying to follow along this tuto :
https://github.com/jofftiquez/vue-stripe-checkout#demo
Here is what I did so far :
Install vue-stripe-checkout package
Declare plugin in my Nuxt.config.js
plugins: [
{ src: "~/plugins/stripeCheckOut.js", ssr: false }
build: {
extend(config, ctx) {
config.module.rules.push({
enforce: "pre",
test: /\.(js|vue)$/,
loader: "eslint-loader",
exclude: /(node_modules)/,
options: {
fix: true
}
});
},
transpile: ["/plugins"]
}
};
Create a plugin
import Vue from 'vue'
import VueStripeCheckout from 'vue-stripe-checkout'
const options = {
key:
'MY KEY', // STRIPE_TOKEN,
locale: 'auto',
currency: 'EUR'
}
Vue.use(VueStripeCheckout, options)
And finaly call this new plugin in my component :
<template>
<div>
<h1>Voici un récapitulatif de votre commande:</h1>
<stripe-checkout
ref="checkoutRef"
:pk="publishableKey"
:items="items"
:success-url="successUrl"
:cancel-url="cancelUrl"
>
<template slot="checkout-button">
<button #click="checkout">
Shut up and take my money!
</button>
</template>
</stripe-checkout>
</div>
</template>
<script>
import { StripeCheckout } from 'vue-stripe-checkout'
export default {
name: 'RecapPrice',
components: {
StripeCheckout
},
data: () => ({
loading: false,
publishableKey: process.env.PUBLISHABLE_KEY,
items: [
{
sku: 'sku_FdQKocNoVzznpJ',
quantity: 1
}
],
successUrl: 'your-success-url',
cancelUrl: 'your-cancel-url'
}),
methods: {
checkout () {
console.log('coucou')
this.$refs.checkoutRef.redirectToCheckout()
}
}
}
</script>
If someone as already implemented Stripe in a Nuxt App, I'd get very happy to get some of your insights
Thanks a lot !

Categories

Resources