How to add vue plugins to Vite? - vuejs3

when i was using webpack instead of vite i used to write this code in app.js
// for File uploads
import vueFilePond from "vue-filepond";
import "filepond/dist/filepond.min.css";
// image preview in file pond
import FilePondPluginImagePreview from "filepond-plugin-image-preview";
import "filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css";
import FilePondPluginFilePoster from "filepond-plugin-file-poster";
import "filepond-plugin-file-poster/dist/filepond-plugin-file-poster.css";
// file size validations
import FilePondPluginFileValidateSize from "filepond-plugin-file-validate-size";
import FilePondPluginFileValidateType from "filepond-plugin-file-validate-type";
const FilePond = vueFilePond(
FilePondPluginImagePreview,
FilePondPluginFilePoster,
FilePondPluginFileValidateSize,
FilePondPluginFileValidateType
);
but now with Vite this is not working.
i tried adding
export default defineConfig({
plugins: [
laravel({
input: [
'resources/js/app.js',
'resources/css/app.css',
],
refresh: true,
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
vueFilePond *****************************this************
],
resolve: {
alias: {
'$': 'jQuery',
},
},
});
this is not working. Please help!

So this worked for me!
// for File uploads
import vueFilePond from "vue-filepond";
import "filepond/dist/filepond.min.css";
// image preview in file pond
import FilePondPluginImagePreview from "filepond-plugin-image-preview";
import "filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css";
import FilePondPluginFilePoster from "filepond-plugin-file-poster";
import "filepond-plugin-file-poster/dist/filepond-plugin-file-poster.css";
// file size validations
import FilePondPluginFileValidateSize from "filepond-plugin-file-validate-size";
import FilePondPluginFileValidateType from "filepond-plugin-file-validate-type";
const FilePond = vueFilePond(
FilePondPluginImagePreview,
FilePondPluginFilePoster,
FilePondPluginFileValidateSize,
FilePondPluginFileValidateType
);
Vue.use(AnyComponent) ; THis was not working in my case
So i tried adding component in below code. this worked for me.
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
setup({ el, app, props, plugin }) {
return createApp({ render: () => h(app, props) })
.use(plugin)
.use(ZiggyVue, Ziggy)
**.mixin({ components: { FilePond } })**
.mount(el);
},
});

Related

Laravel API route doesnt work on vue3 vue-router

Hey everyone laravel 9 vue 3 and vue-router the problem is that localhost:8000/api/admin/login is not available. Transition opens non-existent vue components page Can you suggest how to exclude api prefix from vue router.
Backend: Laravel 9
PHP: 8.0
Fronted: Vue3,axios, vue-routera
web.php
Route::get('{any?}', function () {
return view('welcome');
})->where('any', '.*');
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\Admin\UserController;
Route::any('login', [UserController::class, 'login']);
Route::any('register', [UserController::class, 'register']);
Route::group(['middleware' => 'auth:api'], function () {
Route::get('logout', [UserController::class, 'logout']);
Route::get('user', [UserController::class, 'user']);
});
app.js
import {createApp} from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import axios from 'axios'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(ElementPlus)
app.use(router, axios)
app.config.globalProperties.$axios = axios
app.mount("#app")
router.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Main/HomeComponent.vue';
import Login from './components/Main/LoginComponent.vue';
import Dashboard from './components/Main/DashboardComponent.vue';
const routes = [
{
path: '/',
name: 'home',
component: Home,
meta: {
requiresAuth: false,
title: 'Home',
}
},
{
path: '/login',
name: 'login',
component: Login,
meta: {
requiresAuth: false,
title: 'Login',
}
},
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
requiresAuth: true,
title: 'Dashboard',
}
}
]
const router = createRouter({
history: createWebHistory(),
mode: 'history',
routes,
linkExactActiveClass: 'active'
});
// eslint-disable-next-line no-unused-vars
router.beforeEach((to, from) => {
document.title = to.meta.title;
if (to.meta.requiresAuth === true && !this.$store.authenticated) {
return this.$router.push('/login');
}
})
export default router
In the end, calling api route.php worked correctly

How do I import a 2nd CSS framework (prefixed) into my Vite-based Vue 3 project (1st framework being TailwindCSS)

So I have a default Laravel app working with Vue 3 and assets configured by Vite, TailwindCSS and TailwindUI installed. This all works fine.
I understand to have another CSS framework, I need to prefix it to avoid clashes. According to these instructions, I need to add the following line: (after installing via npm):
import PrimeVue from 'primevue/config'; //I have included this in app.js
as well as reference these styles:
primevue/resources/themes/saga-blue/theme.css
primevue/resources/primevue.min.css
primeicons/primeicons.css
How exactly do I reference these css files with a prefix so as to avoid clashes?
My postcss.config.js file currently looks like this:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
My app.js looks like this:
import './bootstrap';
import '../css/app.css';
import { createApp, h } from 'vue';
import { createInertiaApp } from '#inertiajs/inertia-vue3';
import { InertiaProgress } from '#inertiajs/progress';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { ZiggyVue } from '../../vendor/tightenco/ziggy/dist/vue.m';
/* added by me*/ import PrimeVue from 'primevue/config';
/* added by me*/ import InputMask from 'primevue/inputmask';
const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
setup({ el, app, props, plugin }) {
return createApp({ render: () => h(app, props) })
.use(plugin)
.use(ZiggyVue, Ziggy)
.use(PrimeVue)
/*added by me*/ .component('InputMask', InputMask)
.mount(el);
},
});
InertiaProgress.init({ color: '#4B5563' });

Vue - Use i18n within the setup script

I need to find a way to use the $t of i18n within the setup script for my vue project
my i18n file looks like this:
import { createI18n } from 'vue-i18n'
import en from './en';
import es from './es';
const messages = { en, es };
const locales = [
{ code: 'en', name: 'English' },
{ code: 'es', name: 'Español' }
];
const i18n = createI18n({
locales: locales,
defaultLocale: 'en',
fallbackLocale: 'en',
messages,
silentTranslationWarn: true,
silentFallbackWarn: true,
})
export default i18n
my main js look like this:
import i18n from './lang/settings'
const application = createApp({
render: () => h(app, props)
})
application.use(i18n)
I can perfectly use $t() in the template to translate but I have no clue how to access the same method within <script setup></script>
The i18n resource and the related files need to be placed in the way you have mentioned in your question.
You can use it in this way
I have Added everything in main.ts for better understanding.
you can use it in this way
Main.ts
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { createI18n } from 'vue-i18n';
const i18n = createI18n({
locale: 'en', // set locale
messages: {
en: {
sample:{
item1: 'hello world'
}
}} // set locale messages
});
createApp(App).use(router).use(i18n).mount('#app');
In your component
<script lang="ts" setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n();
let name = t('sample.item1');
</script>
<template>
{{name}}
</template>

The correct way to bundle CSS modules

I have a weird thing happening when my css modules are exported with the * as styles becomes inaccessible when I bundle my code and use it in other repo's.
The response from styles when bundled:
{default: {... my class names} }
When I change my code to import styles from '...' it works when bundled because styles is the default but fails the tests because styles does not have access to the named exports.
rollup config.js
import resolve from '#rollup/plugin-node-resolve'
import commonjs from '#rollup/plugin-commonjs'
import typescript from 'rollup-plugin-typescript2'
import { terser } from 'rollup-plugin-terser'
import postcss from 'rollup-plugin-postcss'
import postCssConfig from '#cinch-labs/postcss-config'
import pkg from './package.json'
import { designTokens, toJSON } from './src/tokens'
const extensions = ['.ts', '.tsx']
// stylelint does work but the postcss one needed to be removed
const postcssPlugins = postCssConfig(toJSON(designTokens)).filter(
({ postcssPlugin }: { postcssPlugin: string }) => postcssPlugin !== 'stylelint',
)
export default [
{
input: './src/index.ts',
output: [
{
file: pkg.main,
format: 'cjs',
},
{
file: pkg.module,
format: 'es',
},
],
plugins: [
postcss({
modules: true,
extract: false,
syntax: 'postcss-scss',
plugins: postcssPlugins,
use: ['sass'],
}),
resolve({
extensions,
}),
commonjs(),
typescript({ tsconfig: 'tsconfig.rollup.json' }),
terser(),
],
external: ['react', 'react-dom'],
},
]
test.component.tsx
import React from 'react'
import classNames from 'classnames'
// I expected the bundler to resolve this for me...
import * as styles from './text.module.scss'
import { TextProps } from './text.types'
export const Text: React.FC<TextProps> = ({
children,
fontSize = 'm',
fontWeight = 'medium',
fontStyle = 'normal',
lineHeight = 'body',
element = 'p',
className,
...props
}) => {
const HtmlEl = element
const classes = classNames(
{
[styles[`textSize${fontSize.toUpperCase()}`]]: fontSize,
[styles[`textWeight${fontWeight.toUpperCase()}`]]: fontWeight,
[styles[`textLineHeight${lineHeight.toUpperCase()}`]]: lineHeight,
[styles[`textFontStyle${fontStyle.toUpperCase()}`]]: fontStyle,
},
className,
)
// classes returns undefined when bundled because of commonjs format.
return (
<HtmlEl className={classes} {...props}>
{children}
</HtmlEl>
)
}
I know this is due to the way common JS works however I would expect for the import * as styles to work. When I change it to import styles from './text.module.scss' it works fine when bundled but does not work in tests.
Using import * as styles from './text.module.scss' you are importing the styles as a named export.
Since this also returns {default: {... my class names} }, you can use styles.default instead, or, perhaps, assign it to a new variable like
const style = styles.default
Fixing this issue was by doing import styles from 'path name' and then installing jest-css-modules to map the styles object in my test.
https://www.npmjs.com/package/jest-css-modules
for me to compile and include with rollup.js the scss into the bundle/build worked adding:
plugins: [
postcss({
modules: true,
extract: false,
syntax: 'postcss-scss',
use: ['sass'],
}),
],
Hope this will help someone else in this journey :)

Storybook custom webpack loading empty scss objects

I added a custom webpack.config.js file to my .storybook project so that I can import .scss files. This is what I added, straight from the storybook docs.
const path = require('path');
// Export a function. Accept the base config as the only param.
module.exports = (storybookBaseConfig, configType) => {
// configType has a value of 'DEVELOPMENT' or 'PRODUCTION'
// You can change the configuration based on that.
// 'PRODUCTION' is used when building the static version of storybook.
// Make whatever fine-grained changes you need
storybookBaseConfig.module.rules.push({
test: /\.scss$/,
loaders: ["style-loader", "css-loader", "sass-loader"],
include: path.resolve(__dirname, '../src')
});
// Return the altered config
return storybookBaseConfig;
};
Here's my story:
import React from 'react';
import { storiesOf } from '#storybook/react'; // eslint-disable-line import/no-extraneous-dependencies
import { action } from '#storybook/addon-actions'; // eslint-disable-line import/no-extraneous-dependencies
import { linkTo } from '#storybook/addon-links'; // eslint-disable-line import/no-extraneous-dependencies
import Button from './'
import ButtonStyles from './index.scss'
import ButtonCompareTrayStyles from './compare-tray.scss'
import ButtonCompareRemminderStyles from './compare-reminder.scss'
console.log({ButtonStyles, ButtonCompareTrayStyles, ButtonCompareRemminderStyles})
storiesOf('Button', module)
.add('with text', () => <Button onClick={action('clicked')}>Hello Button</Button>)
.add('with some emoji', () => <Button onClick={action('clicked')}>😀 😎 👍 💯</Button>)
.add('with default styles', () => <Button styles={ButtonStyles} onClick={action('clicked')}>Hello World</Button>)
.add('with CompareTray styles', () => <Button styles={ButtonCompareTrayStyles} onClick={action('clicked')}>Hello World</Button>)
.add('with CompareRemminder styles', () => <Button styles={ButtonCompareRemminderStyles} onClick={action('clicked')}>Hello World</Button>)
When I log some Button styles, it appears that each one of these objects is empty.
Why are these objects empty? How can I get scss working with storybook?
For everyone who has the same problems, I added the package #storybook/preset-scss and configured it the following way:
module.exports = {
"stories": [
"../src/**/*.stories.*",
"../src/**/*.story.*"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-actions",
"#storybook/addon-essentials",
"#storybook/addon-knobs",
{
name: '#storybook/preset-scss',
options: {
cssLoaderOptions: {
modules: true
}
}
},
]
}
That's it.

Resources