VUE: SFC - use markdown in <docs> tag - vite throwing eror - vuejs2

So I inherited an old (Vue 2) app that uses Styleguidist for creating style guide and documenting components...
It was running extra slow so my first task was to upgrade to using vite instead of webpack. Almost there... fixed almost all the issue, the one is outstanding though... this app uses this format of *.vue components
<template>...</template>
<script>...</script>
<style>...</style>
<docs>
Example of usage
```jsx
<MyComponent>...</MyComponent>
</docs>
where content inside is markdown, so one can write nicer documentation with code example
Now, vite is complaining that I am trying to use jsx (where I am not)...
this is the error
3:36:36 PM [vite] Internal server error: Failed to parse source for
import analysis because the content contains invalid JS syntax. If you
are using JSX, make sure to name the file with the .jsx or .tsx
extension. Plugin: vite:import-analysis
So what am I to do? How do I tell VITE to ignore that part?

The solution, as posted here, is to create a small Vite plugin that ignores the <docs> blocks.
Add this to vite.config.js:
const vueDocsPlugin = {
name: 'vue-docs',
transform(code, id) {
if (!/vue&type=docs/.test(id))
return;
return `export default ''`;
}
};
Then add the plugin to the plugins array:
export default defineConfig({
plugins: [
// vue() will be here...
vueDocsPlugin,
],
});

Related

vuejs/create-vue doesn't support JSX even after you selected "Add JSX Support"

I created new Vue project using create-vue command as it was written here. Here are my answers to questions:
D:\checks>npm init vue#latest
Vue.js - The Progressive JavaScript Framework
√ Project name: ... VueQuestionJSX
√ Package name: ... vuequestionjsx
√ Add TypeScript? ... No
√ Add JSX Support? ... Yes
√ Add Vue Router for Single Page Application development? ... Yes
√ Add Pinia for state management? ... Yes
√ Add Vitest for Unit Testing? ... Yes
√ Add Cypress for End-to-End testing? ... Yes
√ Add ESLint for code quality? ... Yes
√ Add Prettier for code formatting? ... Yes
Scaffolding project in D:\checks\VueQuestionJSX...
Done. Now run
I have not changed any settings in project. I just added simple JSX variable in script
const textDiv = <div>Hi all!</div>;
and decided to check how it works. It didn't. First of all ESlint showed an error Parsing error: Unexpected token <. Then compiler threw an error
[vite] Internal server error: Failed to parse source for import analysis because the content
contains invalid JS syntax. Install #vitejs/plugin-vue to handle .vue files.
Plugin: vite:import-analysis
I checked readme for #vitejs/plugin-vue-jsx and noticed it seems it doesn't understand this usual syntax. First of all component which contains JSX must be exported, and second it must use defineComponent function.
I created a separate file CheckJSX.vue. Here is the whole its content:
CheckJSX.js
import { defineComponent } from "vue";
const Bar = defineComponent({
render() {
return <div>Test</div>;
},
});
export { Bar };
As defineComponent returns Vue Component I inserted Bar as component
HomeView.vue
<script setup>
import { Bar } from "#/components/CheckJSX.js";
</script>
<template>
<Bar />
</template>
ESlint was in shock of this syntax and highlighted everything in red. Probably it didn't like .vue extension. I changed it to .js. ESLint calmed down but still showed an error Parsing error: Unexpected token <.
Compiler threw an error
20:56:29 [vite] Internal server error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
Plugin: vite:import-analysis
File: D:/checks/VueQuestionJSX/src/components/CheckJSX.js
4 | render() {
5 | return <div>Test</div>;
6 | },
| ^
7 | });
Why Vue doesn't understand JSX out of the box even if you chose "Add JSX support"?
A workaround is to enable JSX parsing in the ESLint config:
// .eslintrc.cjs
module.exports = {
⋮
"parserOptions": {
⋮
"ecmaFeatures": {
"jsx": true,
}
}
}
I think this is a new bug because JSX worked previously for me out of the box in a newly scaffolded project. I recommend filing a GitHub issue to get it fixed.

Icons not shown for controls [duplicate]

I have an application that uses UIkit, Less for local styling, and Vite for frontend tooling (bundling and whatnot). I'm not sure that this is relevant, but this is a Vue 2/Webpack application that I'm upgrading to Vue 3/Vite.
Per UIkit's Less documentation, we import UIkit's uikit.theme.less file in our project's base less file. UIkit's stylesheets have some relative paths to SVG files that get run through less's data-uri function (examples below). That worked fine with Webpack, but with Vite it's not quite working. As I understand it, for small files, data-uri will UTF-8 encode the asset and essentially inline it--at least that's what we got in our Webpack bundles. But with our Vite build, it seems these relative image paths aren't being resolved, data-uri hence falls back to a url(), and we get 404s for the images.
For example, in UIkit's code the relative path to a spinner image is defined here; it's used in a select.uk-select. And here that path is passed to a .svg-fill mixin (here). When we bundle the code using Vite, or run a local dev server, the result is:
background-image: url(../../images/backgrounds/form-select.svg);
That, of course, doesn't load because the "images" directory is relative to the form.less file. In Webpack, the output was as expected:
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg width='24' height='16' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%23001c30' d='M12 1 9 6h6zM12 13 9 8h6z'/%3E%3C/svg%3E");
For this type of question, I would normally include an HTML/CSS/JS snippet; however, I don't think SO supports Vite. As such, I'm including a small Stackblitz that minimally demonstrates the issue: https://stackblitz.com/edit/vite-esqmqc?file=main.js Please see main.js, style.less, and note that there's a 404 error in the console complaining about the aforementioned form-select.svg file.
In case the question isn't clear, how can I get Vite to resolve images which are relative to a dependency in node_modules?
Thanks in advance.
A workaround is to configure resolve.alias to point ../../images to uikit/src/images (which resolves to the uikit package under node_modules/). This tells Vite how to resolve the problematic relative image paths.
The resolve.alias config is passed to #rollup/plugin-alias as entries. Each entry can have a custom resolver that can be used to only replace imports from UIKit. However, it requires that the import of uikit.theme.less be in its own file so that the custom resolver can correctly identify the importer in order to determine when to replace the import.
Put the import of uikit.theme.less in its own file, and import that from main.js (not from style.less):
// style.less
// #import './node_modules/uikit/src/less/uikit.theme.less'; ❌ move to own file
// my-uikit.less
#import './node_modules/uikit/src/less/uikit.theme.less';
// main.js
import './style.less';
import './my-uikit.less';
Create vite.config.js with the following configuration:
// vite.config.js
import { defineConfig } from 'vite';
import { fileURLToPath } from 'url';
import { basename } from 'path';
export default defineConfig({
resolve: {
alias: [
{
find: '../../images',
replacement: '',
customResolver(updatedId, importer, resolveOptions) {
// don't replace if importer is not our my-uikit.less
if (basename(importer) !== 'my-uikit.less') {
return '../../images';
}
return fileURLToPath(
new URL(
'./node_modules/uikit/src/images' + updatedId,
import.meta.url
)
);
},
},
],
},
})
demo

Can't parse .mjs module from Iconify. Vue 3 cli using composition api and typescript

Update:
Changing: if(data.aliases?.[name2] !== void 0)
to: if(data.aliases != null && data.aliases[name2] !== void 0)
in the iconify .mjs file fixes the error, however this check occurs a lot of places, and is not viable. Any idea why I cant parse this type of null operator?
in ./node_modules/#iconify/vue/dist/iconify.mjs
Module parse failed: Unexpected token (99:21)You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
My code:
<template>
<div>
<Icon icon="mdi-light:home" />
</div>
</template>
<script setup lang="ts">
import { Icon } from "#iconify/vue";
</script>
Iconify version:
"#iconify/vue": "^3.2.0"
using standard vue cli babel:
presets: ["#vue/cli-plugin-babel/preset"]
I have tried: in babel.config.js
module.exports = function override(config) {
config.module.rules.push({
test: /\.mjs$/,
include: /node_modules/,
type: "javascript/auto"
});
return config;
}
same error
I tried to remove the .mjs file, forcing it to use regular .js file, this resulted in same error but with missing .js loader.
I have tried to use Iconify SVG framework but i get the same type of error where loader is missing for .js files.
Thanks for any feedback :)
Solution:
Downgrading to this version of Iconify "#iconify/vue": "^3.1.1" fixed the problem. This resulted however in a error regarding type declaration. This was fixed by changing VS code's typescript version to: Use workspace version
This is done by selecting a .ts file then pressing "shift+ctrl+p" and select the prompt of select typescript version.
Having the same error cloning from the repository and install dependencies for Vue 2 https://github.com/iconify/iconify
Solution:
Downgrading to this version of Iconify "#iconify/vue": "^3.1.1" fixed the problem. This resulted however in a error regarding type declaration. This was fixed by changing VS code's typescript version to: Use workspace version
This is done by selecting a .ts file then pressing "shift+ctrl+p" and select the prompt of select typescript version.

How to bundle tailwind css inside a Vue Component Package

In one of my projects, I build a nice vue3 component that could be useful to several other projects. So I decided to publish it as an NPM package and share it with everyone.
I wrote the isolate component, build it and publish BUT I use Tailwind css to make the style.
When I publish and install the component everything is working BUT without the beauty of the css part.
I tried several configurations and alternative tools to generate the package that automatically add the tailwind as an inner dependency to my package.
Does someone have experience with this? how can build/bundle my component by adding the tailwind CSS instructions into it?
You're almost there
Since you've got your component working, the majority of the part has been done.
For configuring the styling of the component you need to identify the Tailwind CSS classes being used by your Vue component package and retain them in the final CSS that is generated by the Tailwind engine in your project.
Follow below steps in the project where you want to use your tailwind vue component package.
For Tailwind CSS V3
// tailwind.config.js
module.exports = [
//...
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
"./node_modules/package-name/**/*.{vue,js,ts,jsx,tsx}" // Add this line
// Replace "package-name" with the name of the dependency package
],
//...
]
For Tailwind CSS V2
// tailwind.config.js
module.exports = [
//...
purge: {
//...
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
"./node_modules/package-name/**/*.{vue,js,ts,jsx,tsx}" // Add this line
// Replace "package-name" with the name of the dependency package
],
//...
//...
}
]
The content property in the tailwind.config.js file defines file path pattern that the tailwind engine should look into, for generating the final CSS file.
For Pro users
You may also try to automate the above setup by writing an install script for your npm package to add this configuration to the tailwind.config.js file
References
Tailwind Docs - 3rd party integration
It's a bit difficult for someone to answer your question as you've not really shared the source code, but thankfully (and a bit incorrectly), you've published the src directory to npm.
The core issue here is that when you're building a component library, you are running npm run build:npm which translates to vue-cli-service build --target lib --name getjvNumPad src/index.js.
The index.js reads as follows:
import component from './components/numeric-pad.vue'
// Declare install function executed by Vue.use()
export function install (Vue) {
if (install.installed) return
install.installed = true
Vue.component('getjv-num-pad', component)
}
// Create module definition for Vue.use()
const plugin = {
install
}
// Auto-install when vue is found (eg. in browser via <script> tag)
let GlobalVue = null
if (typeof window !== 'undefined') {
GlobalVue = window.Vue
} else if (typeof global !== 'undefined') {
GlobalVue = global.Vue
}
if (GlobalVue) {
GlobalVue.use(plugin)
}
// To allow use as module (npm/webpack/etc.) export component
export default component
There is no mention of importing any CSS, hence no CSS included in the built version.
The simplest solution would be to include the index.css import in your index.js or the src/components/numeric-pad.vue file under the <style> section.
Lastly, I'm a bit rusty on how components are built, but you might find that Vue outputs the CSS as a separate file. In that case, you would also need to update your package.json to include an exports field.

Vue.js 3 extension breaks while using "vue-cli-service build" due to unsafe-eval

I am developing a chrome extension using vue 3, vue-router and vuex based on Kocal's project which uses vue-cli under the hood. I used whenever possible Single File Components with extensive use of vue bindings.
Everything works perfect on development mode but I recently tried to build the application for production and I encountered this error with partial rendering:
chunk-vendors.f6de00a6.js:11 EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'".
After a few days of digging, my understanding is that either webpack or vue compiling system is messing with CSP by referring/injecting code through eval scripts. As I am fairly new to this, it's hard for me to read to distinguish what I can do.
I tried different approaches:
defining $vue alias to a runtime only build in vue.config.js (supposedly removing unsafe eval by having code compiled before runtime but ending with a new error: Uncaught TypeError: Object(...) is not a function for o=Object(n["withScopeId"])("data-v-21ae70c6");)
using render() function at root
adding "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'", to manifest.json
switching a component to render() to see if I have better chance with the partial rendering, but ending up with nothing being displayed although having console.log from render being executed.
Adding a config to chainWebpack splitting manifest and inline manifest on vue.config
What puzzles me is that I can't shake off the unsafe-eval, with at best a partial display, at worst a blank page. Bindings seem to be shaken off regardless and using a router-link to change page will give a blank page.
Edit: After digging through compiled code from webpack and setting minimize opt to false, it seems the error comes from a vendor: vue-i18n
The eval is likely coming from Webpack, due to an issue with global scoping.
see link for more detail https://mathiasbynens.be/notes/globalthis
Could you try adding this configuration to vue.config.js
module.exports = {
configureWebpack: {
node: {
global: false
},
plugins: [
new webpack.DefinePlugin({
global: "window"
})
]
}
};
tl;dr: Check your dependencies/packages, including those you wouldn't think they use unsafe-eval.
After digging into webpack internals and components building for vue3, here are the takeaways:
using Single File Components and default vue-cli config is ok as it will indeed just need vue runtime, so no unsolicited unsafe-eval
webpack config as below works:
module.exports = {
configureWebpack: {
plugins: [
new webpack.DefinePlugin({
global: "window" // Placeholder for global used in any node_modules
})
]
},
...
};
// Note that this plugin definition would break if you are using "unit-mocha" module for vue-cli
In the end, the issue was a dependency I was using for i18n vue-i18n#next, after removing it and switching to chrome's i18n way, it's now working.