So I'm using vite to build my Vue 3 application for a legacy website which still uses jQuery and a few other JS frameworks.
I'm using the esm bundler as I would still like to boot it up and use it with slotted components.
<div id="app">
<vue-component-name></vue-component-name>
</div>
And it works perfectly. But when jQuery is used on the page, no where near my components it seems the esm bundled version of Vue has set a global variable named $ which breaks jQuery.
Has anyone had this issue or know of a way to fix it?
import { defineConfig } from 'vite';
import type { UserConfig as VitestUserConfigInterface } from 'vitest/config';
import svgLoader from 'vite-svg-loader';
import vue from '#vitejs/plugin-vue';
import path from 'path';
const vitestConfig : VitestUserConfigInterface = {
test: {
globals: true,
include: ['./tests/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
},
};
export default defineConfig({
test: vitestConfig.test,
plugins: [vue(), svgLoader()],
base: '/',
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
'#': path.resolve(__dirname, '/src'),
},
},
build: {
outDir: '../wwwroot/dist',
emptyOutDir: true,
manifest: true,
rollupOptions: {
input: {
main: './src/main.ts',
},
output: {
entryFileNames: 'assets/js/[name].js',
chunkFileNames: 'assets/js/[name].js',
assetFileNames: ({ name }) => {
if (/\.(gif|jpe?g|png|svg)$/.test(name ?? '')) {
return 'assets/images/[name][extname]';
}
if ((name ?? '').endsWith('.css')) {
return 'assets/css/[name][extname]';
}
return 'assets/[name][extname]';
},
globals: {
vue: 'Vue',
},
},
},
},
server: {
hmr: {
protocol: 'ws',
},
},
});
EDIT:
More information, I've tracked this down to using
#input="handleInput($event.target, index)"
This right here breaks existing jQuery. Still no idea how to get around it
For anyone interested, How to wrap Vite build in IIFE and still have all the dependencies bundled into a single file?
Related
I have recently migrated from CRA to Vite. Everything went smooth, yet the build script is throwing an error.
Seems to be a RollupError
Could not resolve "../internals/window" from "../internals/window?commonjs-external"
When I remove the define object from my config, the build succeeds yet the dev server stops working
I am using the vite 4
here is my config
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
import viteTsconfigPaths from "vite-tsconfig-paths";
import svgrPlugin from "vite-plugin-svgr";
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
return {
plugins: [react(), viteTsconfigPaths(), svgrPlugin()],
preview: {
port: 3000,
},
build: {
outDir: "build",
rollupOptions: {
external: ["jss-plugin-window"],
},
},
define: {
global: "window"
},
server: {
open: true,
port: 3000,
},
envPrefix: "REACT_APP_",
};
});
I use the following the bypass the issue, got the solution from here: https://dev.to/lico/issues-that-i-encountered-and-how-to-deal-with-them-while-migrating-from-cra-to-vite-51pg
define: {
...(process.env.NODE_ENV === 'development' ? {global: 'window'} : {})
}
I have a rollup library that is trying to use Antd react components. Without external component libraries, everything works fine. If I add the component library (material ui complains of a similar issue), it complains about trying to import variables that are not exported while importing the component library.
rollup.config.js:
export default [
{
input: 'src/index.ts',
output: [
{
file: packageJson.main,
format: 'cjs',
sourcemap: true,
globals: {
react: 'React',
'react-dom': 'ReactDOM',
},
plugins: [visualizer({ open: useVisualizer })],
},
{
file: packageJson.module,
format: 'esm',
sourcemap: true,
globals: {
react: 'React',
'react-dom': 'ReactDOM',
},
},
],
external: ['react', 'react-dom'],
plugins: [
resolve({
preferBuiltins: true
}),
commonjs({
transformMixedEsModules: true,
requireReturnsDefault: 'auto',
esmExternals: true,
// dynamicRequireTargets: ['node_modules/antd/es/**/*.js']
}),
typescript({ tsconfig: './tsconfig.json' }),
folder(),
postcss({
plugins: [],
}),
eslint(),
terser(),
],
},
{
input: './src/index.ts',
output: [{ file: 'dist/index.d.ts', format: 'esm' }],
plugins: [dts()],
external: [/\.css$/],
},
];
Error message:
[!] Error: 'Group' is not exported by node_modules/antd/es/radio/radio.js, imported by node_modules/antd/es/calendar/Header.js
However, when we look at the exports from radio.js, 'Group' is clearly exported from radio/index.js from within the radio directory:
import Group from './group';
import InternalRadio from './radio';
import Button from './radioButton';
export { Button, Group };
var Radio = InternalRadio;
Radio.Button = Button;
Radio.Group = Group;
Radio.__ANT_RADIO = true;
export default Radio;
Header.js imports this like so: import { Button, Group } from '../radio';, so the import SHOULD be going to radio/index.js, however, it appears it is actually going to radio/radio.js instead. No amount of rollup configuration has made this change so far. Any ideas how to get this to resolve to index.js instead of radio.js?
Turns out the normal node-resolve plugin does not resolve "local" imports (i.e. file system paths instead of package paths). The solution here is to also use rollup-plugin-local-resolve, which does resolve these paths.
My vite.config.ts is:
import { defineConfig } from 'vite';
import react from '#vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
publicDir: './src/assets',
build: {
lib: {
entry: './src/main.tsx',
name: 'index',
fileName: 'index',
formats: ['iife']
}
},
server: {
host: true
}
});
How can I inject in the production script and css automatically in an html index?
like webpack does with html-webpack-plugin.
I'm new to vite (and to webpack too haha) and at least I couldn't find any configuration that would allow me to do something like that, is there a way to do it?
I hope you can help me c:
I am trying to use lottie-player in my vue 3 project but I always get the Warning that Vue failed to resolve the component lottie-player. I am following the official docs of lottieFiles (https://lottiefiles.com/web-player).
The only browser that is not working is Chrome on iOS, for all other tested browsers and operating systems it only throws that warning but it works anyway.
I tried all kind of npm packages but i didn't find any working one for me. My latest idea is to try detecting chrome on iOS and show a different animation there. But of course it would be nice if anyone had a solution for my problem so that I don't get that warning. I mean it would suck if there is no propper way to use lottieFiles in Vue 3, right?lottie docs
Vue warning
I'm currently updating the LottieFiles vue-lottie-player to work with Vue3 and as we wrap the lottie-web player, I was running in to this exact warning too!
Managed to remove it by adding
isCustomElement: tag => tag === 'lottie-player'
inside my vue.config.js file. Heres the full config, you can ignore all the other things:
//Compiler options
const path = require(`path`);
module.exports = {
configureWebpack: {
resolve: {
symlinks: false,
alias: {
vue: path.resolve(`./node_modules/vue`)
}
}
},
chainWebpack: config => {
config.resolve.alias.set('vue', '#vue/compat')
config.module
.rule('vue')
.use('vue-loader')
.tap(options => {
return {
...options,
compilerOptions: {
compatConfig: {
MODE: 2
},
isCustomElement: tag => tag === 'lottie-player'
}
}
})
}
}
Link to the vue player: https://github.com/LottieFiles/lottie-vue
For anyone struggling with Vite2x+ change your vite.config.js file accordingly:
import { fileURLToPath, URL } from 'url'
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue({
template: {
compilerOptions: { //✅ here
isCustomElement: tag => tag === 'lottie-player'
}
}
}) ],
resolve: {
alias: {
'#': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
I am trying to use a component library that I created to reuse in other projects. In it I used loadable-components with webpack and code splitting.
But, when importing into a Next.js project, errors are returned, showing that you cannot import the component from that library.
I have two projects:
Project A = Component library
Project B = Will import Project A
Project B that imported the library (Project A):
(node:20271) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'SomeComponent' of undefined
Config of the imported library (Project A):
webpack.build.config.js
module.exports = {
...
entry: {
[packageName]: './src/index.js'
},
target: 'web',
output: {
chunkFilename: '[chunkhash].chunk.js',
library: packageName,
libraryTarget: 'commonjs2',
globalObject: 'this'
},
externals: nodeExternals(),
optimization: {
minimize: true,
usedExports: true,
splitChunks: {
chunks: 'all',
},
},
plugins: [
new LoadablePlugin()
],
...
}
src/index.js
import styled, { ServerStyleSheet, createGlobalStyle } from 'styled-components';
export * from '#components';
export * from '#style';
export { default as Icons } from '#assets/icons';
export { styled, ServerStyleSheet, createGlobalStyle };
Above, only the #components folder has loadable-components
.babelrc
{
"plugins": [
"styled-components",
[
"#babel/plugin-proposal-pipeline-operator",
{
"proposal": "minimal"
}
],
[
"#babel/plugin-proposal-optional-chaining",
{
"loose": false
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
],
"#loadable/babel-plugin"
]
}
In the Project B, I only import this library with the generated chunks.
But, the same error is always shown, regardless of whether the component is loaded on demand or not.
What am I doing wrong? Any suggestion?
Thanks!