I currently have a React App with Vite 2.7.1. I'm having trouble displaying static local images in Vite while in development.This works in production.
I'm using:
new URL(path, import.meta.url);
And I've tried:
new URL(path, import.meta.url).href;
Then I'd consume it like:
const wavesBg = new URL(
'../../../../resources/images/background-waves.svg', import.meta.url
);
<img src={wavesBg } />
I don't know if this is a file server problem, but it does map the address correctly!
Here's my vite.config.ts file:
export default defineConfig({
plugins: [
viteCommonjs(),
// https://www.npmjs.com/package/#vitejs/plugin-react
react(),
tsconfigPaths(),
eslintPlugin(),
],
resolve: {
alias: {
stream: 'stream-browserify',
'~': path.resolve(__dirname, 'src'),
},
},
server: {
open: true,
fs: {
allow: [
// https://vitejs.dev/config/#server-fs-allow
searchForWorkspaceRoot(process.cwd()),
// This is where I'm serving my images.
'/libs/components/src/resources/images',
],
},
},
optimizeDeps: {
/// Omitted
},
// esbuild: { jsxInject: `import React from 'react'` },
});
Note. Vite is currently configured in a monorepo fashion served using the NX CLI.
Related
I am trying to bundle my Node.js server-side code (Koa app) into a single file which is what Webpack produces when I use the target as node. This is what ncc - node.js compiler collection also achieves.
I am now using Vite for my next project. I am able to bundle the code by using the SSR bundling feature provided by Vite. But I am not able to bundle third-party dependencies into this single file excluding core/built-in node.js modules. This is my Vite build script:
import path from 'path';
import { build } from 'vite';
import builtinModules from 'builtin-modules';
async function main() {
const result = await build({
mode: 'production',
appType: 'custom',
root: path.join(process.cwd(), 'backend'),
ssr: {
format: 'esm',
target: 'node',
// By default Vite bundles everything except the one we pass via `external` array.
external: builtinModules
},
build: {
manifest: false,
rollupOptions: {
input: 'backend/main.mjs',
output: {
assetFileNames: 'bundle.js'
}
},
outDir: '../dist/backend',
ssr: true,
emptyOutDir: true
},
plugins: [],
});
}
main();
In the above code, builtinModules is simply the string array of all the core node.js modules:
// builtinModules
[
'assert', 'async_hooks',
'buffer', 'child_process',
'cluster', 'console',
'constants', 'crypto',
'dgram', 'diagnostics_channel',
'dns', 'domain',
'events', 'fs',
'http', 'http2',
'https', 'inspector',
'module', 'net',
'os', 'path',
'perf_hooks', 'process',
'punycode', 'querystring',
'readline', 'repl',
'stream', 'string_decoder',
'timers', 'tls',
'trace_events', 'tty',
'url', 'util',
'v8', 'vm',
'worker_threads', 'zlib'
]
For my original source code:
// main.mjs
import path from 'path';
import Koa from 'koa';
async function main() {
console.log('Source folder', path.join(__dirname, 'src'));
const app = new Koa();
app.listen(3000);
}
main();
The produced output for the above Vite build configuration is:
// bundle.js
import path from "path";
import Koa from "koa";
async function main() {
console.log("Source folder", path.join(__dirname, "src"));
const app = new Koa();
app.listen(3e3);
}
main();
Ideally, I expected that it would bundle the koa package in the final output leaving behind only native path module. But that's not the case.
So, how do I enable bundling of my entire backend/Node.js source code compile into single file leaving only core node.js modules as external as Node.js is the runtime for my code? The vite server options also provide the noexternal option but setting it to the true works only for webworker like runtime where none of the built-in node modules are available.
Latest vite versions are using preloading you should tweak some rollup options to disable code splitting
import { defineConfig } from 'vite' // 2.8.0
import react from '#vitejs/plugin-react' // 1.0.7
export default defineConfig ({
plugins: [react()],
build: {
rollupOptions: {
output: {
manualChunks: {}
},
},
},
})
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.
we are making a project using django and vue3. In this project, when I run the project with django while the project is running in vue3, django cannot see the App.js and chunk.js files. How can I solve this problem?
vue.config.js
const { defineConfig } = require('#vue/cli-service')
const BundleTracker = require('webpack-bundle-tracker')
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: {
plugins: [
new BundleTracker({ path: __dirname, filename: 'webpack-stats.json' }),
],
},
})
django settings.py
WEBPACK_LOADER = {
'DEFAULT': {
'CACHE': not DEBUG,
'STATS_FILE': str(BASE_DIR.joinpath('frontend', 'webpack-stats.json')),
'POLL_INTERVAL': 0.1,
'IGNORE': [r'.+\.hot-update.js', r'.+\.map'],
}
}
I have a legacy app were we are trying to export some components with WP5 module-federation.
The plugin configuration is currently like this:
output: {
filename: "[name].bundle.js",
},
plugins: [
new ModuleFederationPlugin({
name: "remote",
filename: "remoteEntry.js",
remotes: {},
exposes: {
"./TestExport": path.resolve(__dirname, "../src/TestExport"),
},
shared: {
"react#17": {
singleton: true,
requiredVersion: deps.react,
},
},
}
),
]
the webpack config file is in a config dir in the root folder, this is why we are exposing the component with path.resolve.
When compiling the code, the remoteEntry.js file is not generated and we can't import it in another application using module-federation.
I've tried creating an app and exporting something with module-federation and consuming it inside the legacy app and it worked, but the opposite doesn't work.