How to use vuetify in nuxt js as plugin? - node.js

I need to use vuetify in my nuxt js project as plugin. I've tried package #nuxtjs/vuetify but get error
Cannot assign to read only property 'base' of object '#'
I've install my nuxt project from official codesandbox online playground in local server and on shared hosting. All the time I got the same error. I tried install node modules using npm and yarn. How I can add fresh vuetify version to last version of nuxt js as plugin with npm package vuetify?

Install vuetify and #mdi/font
Create a file vuetify.js in your plugins folder with the following code:
import Vue from 'vue'
import Vuetify from 'vuetify'
import colors from './../config/colors'
import 'vuetify/dist/vuetify.min.css'
import '#mdi/font/css/materialdesignicons.css'
Vue.use(Vuetify)
export default ctx => {
const vuetify = new Vuetify({
theme: {
themes: {
light: {
...colors
},
dark: {
// colors
}
}
}
})
ctx.app.vuetify = vuetify
ctx.$vuetify = vuetify.framework
}
Edit nuxt.config.js file by adding vuetify to plugins like this
{
...
plugins: ['~plugins/vuetify.js'],
...
}

I achieved this with the following:
npm install --save vuetify
create a file vuetify.js in your plugins folder with the following code:
import Vue from 'vue'
import Vuetify from 'vuetify'
Vue.use(Vuetify)
Amend your nuxt.config.js:
plugins: ['~plugins/vuetify.js'],
build: {
vendor: ['vuetify']
}

There is a discussion of this issue here: https://github.com/nuxt-community/vuetify-module/issues/268
Fixing custom colours and specifying options in external files seem to affect this.
If you have colours specified in the options, replace primary: colors.blue with primary: colors.blue.base.

I have / had same issue. I simply made sure to use version 1.10.3 or below defined explicitly in package.json
"#nuxtjs/vuetify": "1.10.3", (not with the ^1.10.3)
I also noticed any version over this also adds an "undefined" 404 to the end of every url request. I posted on Nuxt / CMTY but they have a user base of zero people who answer any questions.

Choose Vuetify as ur UI Framework when initial a Nuxt project
Create a new file in plugins/vuetify.js
import Vue from 'vue'
import Vuetify from 'vuetify'
import colors from 'vuetify/es5/util/colors'
Vue.use(Vuetify)
export default new Vuetify({
theme: {
light: true,
themes: {
light: {
primary: colors.blue.darken2,
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3
}
}
}
})
Add the plugin config inside nuxt.config.js
export default {
plugins: ['~/plugins/vuetify.js'],
}
Restart server, npm run dev
An image example:
vuetify.js
Done!

you can do the following steps in order and finally use Vuetify components:
1- Setup vuetify
yarn add vuetify#next sass
2- Your package.json should now look similar to the following:
// package.json
"devDependencies": {
"nuxt": "3.0.0-rc.1"
},
"dependencies": {
"sass": "^1.51.0",
"vuetify": "^3.0.0-beta.1"
}
3- Creating your Vuetify plugin
You must create this file in the plugin folder and put these codes inside it.
// plugins/vuetify.js
import { createVuetify } from 'vuetify'
import * as components from 'vuetify/components'
import * as directives from 'vuetify/directives'
export default defineNuxtPlugin(nuxtApp => {
const vuetify = createVuetify({
components,
directives,
})
nuxtApp.vueApp.use(vuetify)
})
4- Configure Nuxt 2 or 3 to use our new plugin
In this section, you should put these codes in the nuxt.config.ts file like this
// nuxt.config.ts
import { defineNuxtConfig } from 'nuxt'
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
css: ['vuetify/lib/styles/main.sass'],
build: {
transpile: ['vuetify'],
},
vite: {
define: {
'process.env.DEBUG': false,
},
},
})
5- Finally, in order to test that you have done the steps correctly, you can use this component in your code to see if Vuetify is installed correctly or not.
<v-btn>Button</v-btn>
Tip: If you have done these steps or you want to use a new component, in many cases it is better to stop and restart your project once.

Related

How to configure react typescript project having folder paths accessible like '#components/'

I want to change the relative url imports for react-typescript project. Basically from this crap ../../../contexts/AuthContext to just clean #contexts/AuthContexts.
I have tried the following with tsconfig.json :
"compilerOptions": {
"paths": {
"#components/*": ["src/components/*"],
"#contexts/*": ["src/contexts/*"]
}
}
But I am still getting error like #contexts/AuthContexts not found. And yes I can confirm that there is a file called AuthContext in that location with exports as AuthProvider.
I have created this app with npm create vite#latest using typescript as a template.
Any help will be highly appreciated.
You need to set resolve.alias in vite.config.ts file
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
import path from "path";
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"#components": path.resolve(__dirname, "src/components"),
},
},
});

Vitest alias or inline.deps fail to resolve import error

I am migrating some jest tests over to vitest and some of my tests are failing due to an import issue of an external package dependency in node_modules. Specifically: #package/dependency seems to be an ES Module but shipped in a CommonJS package.
vitest suggests this change to my config:
export default {
test: {
deps: {
inline: [
"#package"
]
}
}
}
Unfortunately, this fix does not work. Previously I resolved this issue with moduleNameMapper in jest where "#package/dependency": "#package/dependency/js" mapped to a valid import. I tried setting alias in both test.alias and resolve.alias, but neither works.
I am using Typescript in this project, and the rest of my test config looks like this:
test: {
globals: true,
environment: "jsdom",
setupFiles: "./src/setupTests.js",
}
// setupTests.js
import {configure} from 'enzyme/build';
import Adapter from 'enzyme-adapter-react-16/build';
configure({ adapter: new Adapter() });
What can I do to get around this? Thanks.

Vite: Including files in build output

This is a Vue 3 + Vuetify + TS + Vite + VSCode project.
I'm trying to bundle an XML file in the production build. Some transformation needs to be applied on the file before spitting it out. Found this Vite plug-in that can do transformations. But unfortunately, it doesn't seem to touch XML files in any way. If I put my XML file in public folder, it gets copied to the build output, but is not processed by the transformation plugin. If I put it in assets or somewhere else under src, it is simply ignored.
How can I ask Vite to include certain file(s) in the build output and pass it through transformation?
Note: Before I migrated the project to Vite, I was using Vue 2 and WebPack, where I could use the well-known CopyWebpackPlugin to perform this transformation. Haven't been able to find locate its Vite equivalent till now.
You may want to just write a script to do the transformation and add it to your npm scripts. I created a simple chrome extension to play around with VITE. Having multiple html files was pretty simple:
import { defineConfig, BuildOptions } from 'vite'
import vue from '#vitejs/plugin-vue'
const { resolve } = require('path')
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
build: {
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
popup: resolve(__dirname, 'popup/index.html'),
options: resolve(__dirname, 'options/index.html'),
},
}
}
})
But I had to create a separate vite config file to process the background script since it had special configuration (didn't want hashing so I could specify the name in my manifest, esm module format), and it takes the typescript and outputs 'background.js' in the public folder:
import { defineConfig } from 'vite'
const { resolve } = require('path')
// https://vitejs.dev/config/
export default defineConfig({
build: {
emptyOutDir: false,
rollupOptions: {
input: resolve(__dirname, 'background.ts'),
output: {
format: "esm",
file: "public/background.js",
dir: null,
}
}
}
})
You could simply have the xml file in your src folder and run a special script (create a 'scripts' folder maybe) to do the transform and store the result in the public folder where vite will pick it up and copy it to the dist folder. Your 'build' script in package.json could look something like this:
"scripts": {
"build": "node scripts/transform-xml.mjs && vite build",
},
Author of the package has introduced a new option named replaceFiles in the version 2.0.1 using which you can specify the files that will be passed through the transform pipeline. I can now do the following in my vite.config.js to replace variables in my output manifest.xml file after build:
const replaceFiles = [resolve(join(__dirname, '/dist/manifest.xml'))];
return defineConfig({
...
plugins: [
vue(),
transformPlugin({
replaceFiles,
replace: {
VERSION_NUMBER: process.env.VITE_APP_VERSION,
SERVER_URL: process.env.VITE_SERVER_URL,
},
...
}),
...
});

React component bundle for consuming by browser and node (react hooks issue)

I have seriously headache because of this issue.
Source code - https://github.com/marekkobida/stackoverflow
UPDATE - without React hooks everything works...
Issue
I am trying to build a single bundle (react component) for browser and node via webpack bundler for SSR purposes. Node should swallow that bundle as described here:
const React = require("react");
const ReactDOMServer = require("react-dom/server");
const Test = require("./public/index.js").default; // ✅ React Component (works)
ReactDOMServer.renderToString(React.createElement(Test)); // Error
but an error appears:
Error: Invalid hook call. Hooks can only be called inside of the body
of a function component. This could happen for one of the following
reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
BUT browser version works. However after adding externals into webpack configuration, the node version works and browser does not.
React component file before bundling via webpack bundler
import React from "react";
import ReactDOM from "react-dom";
function Test() {
const [_, __] = React.useState(1);
return React.createElement("div", null, _); // ✅ <div>1</div> (works)
}
if (typeof window !== "undefined") { // because of UMD
ReactDOM.render(React.createElement(Test), document.getElementById("index")); // ✅ (works)
}
export default Test; // ✅
webpack configuration file
...
{
entry: "./index.js", // File described above
// The node version will work but the browser version will stop working after uncommenting the lines below
//
// externals: {
// react: 'react',
// 'react-dom': 'react-dom'
// },
mode: "development",
output: {
filename: "index.js",
globalObject: "this",
libraryTarget: "umd",
path: path.resolve("./public"),
publicPath: "",
},
},
...
BUT browser version works. However after adding externals into webpack configuration, the node version works and browser does not.
This maybe considered a workaround, but you could use two separate webpack configs, one for the node and the other for the browser version.
Edit:
Also for the node version not working: You're only have a require for ReactDOMServer, but not for ReactDom itself, maybe that is a problem, too.
I'm using this form, maybe give it a try:
externals: {
"react": {
"commonjs": "react",
"commonjs2": "react",
"amd": "react",
"root": "React"
},
"react-dom": {
"commonjs": "react-dom",
"commonjs2": "react-dom",
"amd": "react-dom",
"root": "ReactDom"
},
},

Vite library with Windicss

I am using Vite (Vue3) with Windi CSS to develop a library. I am using library mode for the build (https://vitejs.dev/guide/build.html#library-mode) with the following config:
vite.config.js
export default defineConfig({
plugins: [vue(), WindiCSS()],
build: {
lib: {
entry: path.resolve(__dirname, 'src/lib.js'),
name: 'MyLIB',
},
rollupOptions: {
// make sure to externalize deps that shouldn't be bundled
// into your library
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
vue: 'Vue',
},
},
},
},
});
My entry file (src/lib.js) only includes a few Vue components in it and looks like this:
lib.js
export { default as AButton } from './components/AButton/AButton.vue';
export { default as ACheckbox } from './components/ACheckbox/ACheckbox.vue';
import 'virtual:windi.css';
import './assets/fonts.css';
When I build the library I get the js for just those components but the css is for every Vue file in the src folder and not only the ones i included in my lib.js file. I know the default behavior for Windi CSS is to scan the whole src folder but in this case, I only want it to scan the components I added to my entry.
Any ideas?
You should be able to restrict the scan by using extract.include and extract.exclude options, see there : https://windicss.org/guide/extractions.html#scanning
From the doc
If you want to enable/disable scanning for other file-types or locations, you can configure it using include and exclude options

Resources