I have like this configuration file in my vue.js + vite.js project:
File vite.config.js:
import { defineConfig, loadEnv } from 'vite'
import svgLoader from 'vite-svg-loader'
import vue from '#vitejs/plugin-vue'
import path from 'path'
const generateScopedName = 'tw_[local]'
export default ({ mode }) => {
process.env = {...process.env, ...loadEnv(mode, process.cwd(), '')};
return defineConfig({
define: {
'process.env': process.env
},
build: {
sourcemap: false,
cssCodeSplit: false,
rollupOptions: {
output: {
dir: 'dist',
chunkFileNames: '[name].js'
}
}
},
resolve: {
alias: {
'#': path.resolve(__dirname, './src')
}
},
server: {
fs: {
allow: ['..']
},
hmr: {
overlay: false
}
},
plugins: [vue(), svgLoader()],
css: {
modules: {
generateScopedName
}
}
});
}
When I build my project by running command vite build then value of defined process.env variable will be saved as static value from current .env file values. But when I put my bulded projec to another place with different .env file then value of defined process.env won't update automatically. How I can correctly watch .env file values for changes on static build if it possible of course?
Related
Locally, Vite builds just fine. However, in CI (which just runs the same script, npm run build), it fails.
I get this error in CI:
Error: "Buffer" is not exported by "__vite-browser-external", imported by "src/index.html?html-proxy&index=0.js".
file: /home/runner/work/explorer/explorer/src/index.html?html-proxy&index=0.js:2:13
1:
2: import { Buffer } from "buffer";
^
3: window.Buffer = Buffer;
Error: error during build:
RollupError: "Buffer" is not exported by "__vite-browser-external", imported by "src/index.html?html-proxy&index=0.js".
I added the line that is causing the error because of an issue when running vite serve locally (it errors) - StackOverflow suggested this solution. It builds fine even in CI without that line.
Here's my Vite config:
import { defineConfig } from 'vite'
import react from '#vitejs/plugin-react'
import viteTsconfigPaths from 'vite-tsconfig-paths'
import svgrPlugin from 'vite-plugin-svgr'
import { createHtmlPlugin } from 'vite-plugin-html'
import EnvironmentPlugin from 'vite-plugin-environment'
import { NodeGlobalsPolyfillPlugin } from '#esbuild-plugins/node-globals-polyfill'
export default defineConfig({
root: './src',
envDir: '..',
build: {
// relative to the root
outDir: '../build',
},
// relative to the root
publicDir: '../public',
server: {
open: true,
port: 3000,
proxy: {
'/api': 'http://localhost:5001',
},
},
define: { 'process.env': {} },
resolve: {
alias: {
events: 'events',
stream: 'stream-browserify',
zlib: 'browserify-zlib',
'util/': 'util',
},
},
optimizeDeps: {
esbuildOptions: {
define: {
// Node.js global to browser globalThis
global: 'globalThis',
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
buffer: true,
}),
],
},
},
plugins: [
svgrPlugin({
exportAsDefault: true,
}),
react({
// Use React plugin in all *.jsx and *.tsx files
include: '**/*.{jsx,tsx}',
}),
createHtmlPlugin({
inject: {
data: {
VITE_GA_ID: process.env.VITE_GA_ID,
VITE_ZENDESK_KEY: process.env.VITE_ZENDESK_KEY,
},
},
}),
EnvironmentPlugin('all'),
NodeGlobalsPolyfillPlugin({
buffer: true,
process: true,
}),
viteTsconfigPaths(),
],
test: {
globals: true,
setupFiles: 'src/setupTests.js',
},
})
My build command is DISABLE_NEW_JSX_TRANSFORM=true vite build --emptyOutDir
My serve command is DISABLE_NEW_JSX_TRANSFORM=true vite serve
I use VueJS version 2 with Vite v3.2.5 and when I load my website I get this error in Firefox:
Loading of the module from ".../build/app.mjs" was blocked due to an unapproved MIME type ("application/octet-stream").
CSS/SCSS is working and I have only problems with the app.js/app.mjs.
Is it possible to change the output of my file from app.mjs to app.js?
This is my vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '#vitejs/plugin-vue2';
const path = require('path')
import { resolve } from 'path'
export default defineConfig({
plugins: [
laravel({
hotFile: 'public/widget.hot',
input: [
'resources/js/app.js',
'resources/scss/app.scss',
'resources/scss/index.scss'
],
refresh: true,
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
server: {
host: true
},
resolve: {
alias: {
vue: 'vue/dist/vue.esm.js',
},
dedupe: [
'vue'
]
},
alias: {
'~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'),
},
build: {
cssCodeSplit: true,
lib: {
input: {
app: "./resources/js/app.js"
},
formats: ['es'],
entry: resolve(__dirname, 'resources/js/app.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
name: 'bundle',
fileName: 'app'
},
rollupOptions: {
external: ['vue'],
output: {
globals: {
vue: 'Vue',
},
//format: "esm",
inlineDynamicImports: false,
},
},
},
});
I have this in my blade.php file:
#vite('resources/js/app.js')
Does anyone how to fix it?
Thanks for help!
Try adding the mime type for .mjs files in the Plesk control panel (based on their docs):
If this is a Linux server
Log in to Plesk.
Go to Domains > YOUR DOMAIN NAME > Apache & nginx Settings.
Next to MIME types, select the Enter custom value option button.
Add a line that says: text/javascript .mjs.
Save your changes.
If this is a Windows server
Log in to Plesk.
Go to Domains > YOUR DOMAIN NAME > Hosting Settings > IIS Settings.
Go to the MIME Types section.
Add a line that says: text/javascript .mjs.
Save your changes.
I have a vite SPA and use dynamic imports to load my json files. Since I need to load numerous very large json files, the index.js file in my /dist becomes too big in my production build.
What is the best way to import these json files dynamically but still keep small chunks? Can I import somehow the json files dynamically as own chunks, similar to images and videos with hashes?
Here my vite.config.js
import path from 'path'
import { defineConfig } from 'vite'
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'
import { createHtmlPlugin } from 'vite-plugin-html'
import svgr from 'vite-plugin-svgr'
import legacy from '#vitejs/plugin-legacy'
import react from '#vitejs/plugin-react'
import { name } from './package.json'
export default defineConfig({
base: '/widgets/' + name + '/',
server: {
open: true, // Define a BROWSER in your .env-File to specify which browser. Defaults to Chrome. https://vitejs.dev/config/#server-open
port: 3000,
},
resolve: {
alias: {
'#Assets': path.resolve(__dirname, 'src/assets'),
'#Components': path.resolve(__dirname, 'src/components'),
'#Examples': path.resolve(__dirname, 'src/examples'),
'#Scripts': path.resolve(__dirname, 'src/scripts'),
'#Styles': path.resolve(__dirname, 'src/assets/styles'),
'#Cms': path.resolve(__dirname, 'src/assets/styles/cms'),
},
},
css: {
devSourcemap: true, // needed for css imported in cms template
},
define: {
__DATA_PATH__: JSON.stringify(process.env.npm_package_config_dataPath),
},
build: {
rollupOptions: {
output: {
entryFileNames: `[name].js`,
chunkFileNames: `[name].js`,
assetFileNames: `[name].[ext]`,
},
},
},
plugins: [
legacy({
polyfills: true,
}),
react(),
createHtmlPlugin({
minify: true,
inject: {
data: {
title: name,
id: name,
},
},
}),
cssInjectedByJsPlugin(),
svgr(),
],
})
You can try this configuration:
// vite.config.ts
build: {
chunkSizeWarningLimit: 500, // default 500 KB
},
https://vitejs.dev/config/build-options.html#build-chunksizewarninglimit
I am working on a chrome extension using vuejs currently i have a ready project to start with but it is with webpack.
In the webpack I have multi-entry points some of which lead to generating HTML files and others with javascript only.
with webpack it is clear what is the inputs and how they will be as output in Vite i tried but there is a lot of plugins outdated that work with vuejs 3
this link contains the project
https://stackblitz.com/edit/vue-v83gga
my webpack file is :
const path = require("path");
const fs = require("fs");
// Generate pages object
const pages = {};
function getEntryFile(entryPath) {
let files = fs.readdirSync(entryPath);
return files;
}
const chromeName = getEntryFile(path.resolve(`src/entry`));
function getFileExtension(filename) {
return /[.]/.exec(filename) ? /[^.]+$/.exec(filename)[0] : undefined;
}
chromeName.forEach((name) => {
const fileExtension = getFileExtension(name);
const fileName = name.replace("." + fileExtension, "");
pages[fileName] = {
entry: `src/entry/${name}`,
template: "public/index.html",
filename: `${fileName}.html`,
};
});
const isDevMode = process.env.NODE_ENV === "development";
module.exports = {
pages,
filenameHashing: false,
chainWebpack: (config) => {
config.plugin("copy").use(require("copy-webpack-plugin"), [
{
patterns: [
{
from: path.resolve(`src/manifest.${process.env.NODE_ENV}.json`),
to: `${path.resolve("dist")}/manifest.json`,
},
{
from: path.resolve(`public/`),
to: `${path.resolve("dist")}/`,
},
],
},
]);
},
configureWebpack: {
output: {
filename: `[name].js`,
chunkFilename: `[name].js`,
},
devtool: isDevMode ? "inline-source-map" : false,
},
css: {
extract: false, // Make sure the css is the same
},
};
i finally find out a solution for it as a pre-build template by vitesse written with typescript
https://github.com/antfu/vitesse-webext
in short answer if you want to have multiple entries of HTML files you can add them to the original vite.config.js file
regarding the content.ts file, it needs a different vite.config.content.ts file and we have to call it when we build the project like this
vite build && vite build --config vite.config.content.ts
regarding the vite.config.ts file, the code will be like this written in typescript
/// <reference types="vitest" />
import { dirname, relative } from 'path'
import type { UserConfig } from 'vite'
import { defineConfig } from 'vite'
import Vue from '#vitejs/plugin-vue'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import WindiCSS from 'vite-plugin-windicss'
import windiConfig from './windi.config'
import { isDev, port, r } from './scripts/utils'
export const sharedConfig: UserConfig = {
root: r('src'),
resolve: {
alias: {
'~/': `${r('src')}/`,
},
},
define: {
__DEV__: isDev,
},
plugins: [
Vue(),
AutoImport({
imports: [
'vue',
{
'webextension-polyfill': [
['*', 'browser'],
],
},
],
dts: r('src/auto-imports.d.ts'),
}),
// https://github.com/antfu/unplugin-vue-components
Components({
dirs: [r('src/components')],
// generate `components.d.ts` for ts support with Volar
dts: r('src/components.d.ts'),
resolvers: [
// auto import icons
IconsResolver({
componentPrefix: '',
}),
],
}),
// https://github.com/antfu/unplugin-icons
Icons(),
// rewrite assets to use relative path
{
name: 'assets-rewrite',
enforce: 'post',
apply: 'build',
transformIndexHtml(html, { path }) {
return html.replace(/"\/assets\//g, `"${relative(dirname(path), '/assets')}/`)
},
},
],
optimizeDeps: {
include: [
'vue',
'#vueuse/core',
'webextension-polyfill',
],
exclude: [
'vue-demi',
],
},
}
export default defineConfig(({ command }) => ({
...sharedConfig,
base: command === 'serve' ? `http://localhost:${port}/` : '/dist/',
server: {
port,
hmr: {
host: 'localhost',
},
},
build: {
outDir: r('extension/dist'),
emptyOutDir: false,
sourcemap: isDev ? 'inline' : false,
// https://developer.chrome.com/docs/webstore/program_policies/#:~:text=Code%20Readability%20Requirements
terserOptions: {
mangle: false,
},
rollupOptions: {
input: {
background: r('src/background/index.html'),
options: r('src/options/index.html'),
popup: r('src/popup/index.html'),
},
},
},
plugins: [
...sharedConfig.plugins!,
// https://github.com/antfu/vite-plugin-windicss
WindiCSS({
config: windiConfig,
}),
],
test: {
globals: true,
environment: 'jsdom',
},
}))
the important part of it is this
vite.config.ts
...
build: {
outDir: r('extension/dist'),
emptyOutDir: false,
sourcemap: isDev ? 'inline' : false,
// https://developer.chrome.com/docs/webstore/program_policies/#:~:text=Code%20Readability%20Requirements
terserOptions: {
mangle: false,
},
rollupOptions: {
input: {
background: r('src/background/index.html'),
options: r('src/options/index.html'),
popup: r('src/popup/index.html'),
},
},
},
...
Thank you to anyone who tried to help and I hope this will be helpful to others
Regards
I've succesfully added vite to my project. It builds fine for prodiction. However in Production I have an error
Uncaught ReferenceError: describe is not defined
at index.ba9d79ff.js:1119:1426
I then saw the my .spec files where being added. I thought vite would of handled the removal of the test files. I want to remove my .spec files from production.
but not having such luck. I'm using Vue 2 with vite. I added
production: {
exclude: ['src/components/**/*.{spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
},
but the files are still being added. Is there something more I need to do?
My config
import { defineConfig } from "vite";
import { createVuePlugin as vue } from "vite-plugin-vue2";
import { VuetifyResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
// https://vitejs.dev/config/const
const path = require("path");
export default defineConfig({
plugins: [
vue(),
Components({
resolvers: [
// Vuetify
VuetifyResolver(),
],
}),
],
resolve: {
extensions: [
".mjs",
".js",
".ts",
".jsx",
".tsx",
".json",
".vue",
".scss",
],
alias: {
"#": path.resolve(__dirname, "./src"),
json2csv: "json2csv/dist/json2csv.umd.js",
"~bootstrap": "bootstrap",
},
},
production: {
exclude: ['src/components/**/*.{spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
},
extensions: etc,
css: {
preprocessorOptions: {
scss: {
// additionalData: `#import "src/scss/app.scss";`,
// additionalData: `#import "src/scss/_variables.scss";`,
sourceMap: false,
additionalData(source, fp) {
// All scss files ending with imports.scss
// will not re-import additionalData
if (fp.endsWith("_variables.scss")) return source;
// Use additionalData from legacy nuxt scss options
// return `#import "#/assets/mixin.scss"; ${source}`;
return `#import "src/scss/_variables.scss"; ${source}`;
},
},
},
},
server: {
port: 8090,
},
});