How to make create-vue parse JSX without problems (as VueCLI does) - vue.js

I use JSX extensively to customize Naive-UI library elements. But after migrating from VueCLI to create-vue, I noticed it looks like create-vue doesn't understand JSX in .vue file at all. For example it throws Uncaught SyntaxError: Unexpected token '<' for this:
const x = <div>Hi all</div>;
But VueCLI does understand... So the question is:
How to make create-vue parse JSX without problems (as VueCLI does)?
PS. Here is vite.config.js
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
import vueJsx from "#vitejs/plugin-vue-jsx";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
},
});

To use JSX in .vue files, make sure to use <script lang="jsx"> (or "tsx" if using TypeScript)

Related

The requested module '/node_modules/.vite/deps/vue.js' does not provide an export named 'default'

The following is my problem.
I packaged my project through vite in library mode. The error occurs whenever my library includes any third party UI library (e.g vue-loading-overlay). But other libraries like moment.js will have no problem.
This is my vite.config.js, Is there any problem with my configuration?
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
export default defineConfig({
plugins: [vue()],
build: {
lib: {
entry: resolve(__dirname, "src/lib.ts"),
name: "my-ui-lib",
fileName: "my-ui-lib",
},
rollupOptions: {
external: ["vue"],
output: [
{
format: "es",
exports: "named",
globals: { vue: "vue" },
},
],
},
},
});
Finally I resolved my problem, Adding the following in vite.config.js. It works for me.
build: {
/** If you set esmExternals to true, this plugins assumes that
all external dependencies are ES modules */
commonjsOptions: {
esmExternals: true
},
}
Original Answer
"Chart.js V3 is treeshakable so you need to import and register everything or if you want everything you need to import the chart from the auto import like so:
change
import Chart from 'chart.js'
to ->
import Chart from 'chart.js/auto';
For more information about the different ways of importing and using chart.js you can read the integration page in the docs.
Since you are upgrading from Chart.js V2 you might also want to read the migration guide since there are some major breaking changes between V2 and V3"
/* Adding the following in vite.config.js. Just copy and paste all these code. It works for me. */
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
commonjsOptions: {
esmExternals: true,
},
});
react-pdf v6 has a pretty clever solution for this, look at their entry files. I think the point is to link to the correct file, somehow there's no need to "actually" import the worker (it doesn't run on main thread anyway I guess? New to worker and pdfjs).
import * as pdfjs from 'pdfjs-dist/build/pdf';
pdfjs.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.js', import.meta.url);
import.meta availability.
Refer to vuejs 3 documentation to import vue.

Path aliases not working in vue script block

I'm trying to completely understand the path aliases with Vue and Vite.
Outside of the <script> block (e.g. <style> and <template> or other .js files) absolute paths with ~ or the # alias, for getting the root directory are working. But inside I still need to use ../../../ for getting back to the root. If I try using ~ or # I get errors for files not being found.
Also wouldn't # and ~ do the same in that case?
EDIT:
// Somehow working cause it's no component but a mere .js file
import {
filterwords
} from '#/services/signup/filterwords.js';
// Working
import passwordMeter from '../../utility/PasswordMeter.vue';
// Not working
import passwordMeter from '~/utility/PasswordMeter.vue';
import passwordMeter from '#/utility/PasswordMeter.vue';
Do proper changes in vite.config.js. Tested this locally and it solves it.
Add '~' if you also want to use that.
// vite.config.js
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
const path = require('path')
// https://vitejs.dev/config/
export default defineConfig({
resolve:{
alias:{
'#' : path.resolve(__dirname, './src')
},
},
plugins: [vue()]
})
Credit to this article: https://vueschool.io/articles/vuejs-tutorials/import-aliases-in-vite/

How to fix the asset file path in my Vue (Vite) application build?

I recently completed a small project in Vue, but when I uploaded it to my server, I am just seeing a blank screen. From my research, I discovered it was likely an issue relating to the asset path as I had it in a sub-directory (https://digitalspaces.dev/portfolio/wil/). After some time trying to fix it by editing the vite.config.js file, I gave up and decided to host it in a subdomain (https://wil.digitalspaces.dev/) instead, where it is now.
The problem is, the index.html now thinks the assets files are at https://digitalspaces.dev/portfolio/wil/assets/, which is true I suppose, but they don't seem to be working from there (nor should they be). Frustratingly, when the build is in https://digitalspaces.dev/assets/, the assets directory is https://digitalspaces.dev/assets/, so it's broken no matter where I have it.
I based my project on the Vue.js quick start guide using vite.
My complete repo is on GitHub, and this is the vite.config.js file:
import { fileURLToPath, URL } from 'url'
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import vueJsx from '#vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
'#': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
Thanks to anyone who is able to help.
The subdirectory on your site is /portfolio/wii/, so you should configure the base URL to match:
// vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({
⋮
base: '/portfolio/wii/'
})

Web3js fails to import in Vue3 composition api project

I've created a brand new project with npm init vite bar -- --template vue. I've done an npm install web3 and I can see my package-lock.json includes this package. My node_modules directory also includes the web3 modules.
So then I added this line to main.js:
import { createApp } from 'vue'
import App from './App.vue'
import Web3 from 'web3' <-- This line
createApp(App).mount('#app')
And I get the following error:
I don't understand what is going on here. I'm fairly new to using npm so I'm not super sure what to Google. The errors are coming from node_modules/web3/lib/index.js, node_modules/web3-core/lib/index.js, node_modules/web3-core-requestmanager/lib/index.js, and finally node_modules/util/util.js. I suspect it has to do with one of these:
I'm using Vue 3
I'm using Vue 3 Composition API
I'm using Vue 3 Composition API SFC <script setup> tag (but I imported it in main.js so I don't think it is this one)
web3js is in Typescript and my Vue3 project is not configured for Typescript
But as I am fairly new to JavaScript and Vue and Web3 I am not sure how to focus my Googling on this error. My background is Python, Go, Terraform. Basically the back end of the back end. Front end JavaScript is new to me.
How do I go about resolving this issue?
Option 1: Polyfill Node globals/modules
Polyfilling the Node globals and modules enables the web3 import to run in the browser:
Install the ESBuild plugins that polyfill Node globals/modules:
npm i -D #esbuild-plugins/node-globals-polyfill
npm i -D #esbuild-plugins/node-modules-polyfill
Configure optimizeDeps.esbuildOptions to use these ESBuild plugins.
Configure define to replace global with globalThis (the browser equivalent).
import { defineConfig } from 'vite'
import GlobalsPolyfills from '#esbuild-plugins/node-globals-polyfill'
import NodeModulesPolyfills from '#esbuild-plugins/node-modules-polyfill'
export default defineConfig({
⋮
optimizeDeps: {
esbuildOptions: {
2️⃣
plugins: [
NodeModulesPolyfills(),
GlobalsPolyfills({
process: true,
buffer: true,
}),
],
3️⃣
define: {
global: 'globalThis',
},
},
},
})
demo 1
Note: The polyfills add considerable size to the build output.
Option 2: Use pre-bundled script
web3 distributes a bundled script at web3/dist/web3.min.js, which can run in the browser without any configuration (listed as "pure js"). You could configure a resolve.alias to pull in that file:
import { defineConfig } from 'vite'
export default defineConfig({
⋮
resolve: {
alias: {
web3: 'web3/dist/web3.min.js',
},
// or
alias: [
{
find: 'web3',
replacement: 'web3/dist/web3.min.js',
},
],
},
})
demo 2
Note: This option produces 469.4 KiB smaller output than Option 1.
You can avoid the Uncaught ReferenceError: process is not defined error by adding this in your vite config
export default defineConfig({
// ...
define: {
'process.env': process.env
}
})
I found the best solution.
The problem is because you lose window.process variable, and process exists only on node, not the browser.
So you should inject it to browser when the app loads.
Add this line to your app:
window.process = {
...window.process,
};

import vue-awesome icons error while jest testing with nuxt on node 13.9.0

I have followed the instructions on https://github.com/Justineo/vue-awesome
in my jest.config.js I add the following
transformIgnorePatterns: [
'/node_modules(?![\\\\/]vue-awesome[\\\\/])/'
]
my nuxt.config.js
build: {
transpile: [/^vue-awesome/] // enable font-awesome integration.
},
The icons work just fine when I'm running the dev box, but I get the following when I run yarn test:
[path/to/project]/node_modules/vue-awesome/icons/building.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue'
^^^^^^
SyntaxError: Cannot use import statement outside a module
explicitly, the issue seems to be something to do with how babel reads (or overlooks) the imports above the Icon component import. So, for example, given the building.js in the error log above, here is how the import looks in the vuejs file:
<script>
import 'vue-awesome/icons/building'
import Icon from 'vue-awesome/components/Icon'
export default {
componentes: {
'v-icon': Icon
}
...
}
</script>
It looks like I have to explicitly mock the component and its imports at the top of the file (below the imports)
the following works for my test.
import { shallowMount, createLocalVue } from '#vue/test-utils'
import Vuex from 'vuex'
import { AxiosSpy, MockNuxt } from 'jest-nuxt-helper'
import index from '#/pages/courses/index'
// MOCKS:
jest.mock('vue-awesome/icons/building', () => '')
jest.mock('vue-awesome/components/Icon', () => '<div></div>')
...