Vue 3 & Vite built application shows blank page - javascript

I have a problem trying to make a build of a new Vue3.js + Vite.js application. Once my application is finished i made the npm run build action in order to generate the final deployment files.
Problem is that when I try to see the generated page, it only shows a white page.
Opening the inspection tool I can see how the main generated javascript files are like not being found by the static index.html:
Failed to load resource: net::ERR_FAILED index.7b66f7af.js:1

Ok. I found the solution searching a bit, and I see how this problem also occurred actually in Vue 2.
The only thing that you have to do for solvif is add base: './' in your vite.config.js, like this:
import {
defineConfig
} from 'vite'
import vue from '#vitejs/plugin-vue'
import vuetify from '#vuetify/vite-plugin'
const path = require('path')
export default defineConfig({
plugins: [
vue(),
vuetify({
autoImport: true,
}),
],
define: {
'process.env': {}
},
resolve: {
alias: {
'#': path.resolve(__dirname, 'src'),
},
},
base: './',
})
Hope it helps you all!

I had this problem also, and found a solution:
It looks like the awnser given by #javi But it's different. I found out that the situation changes when you deploy your application.
In vite config there is a setting called 'base' filled in like: base: mode === 'production' ? '/nameExample/' : '/', this will put the output of your project on the endpoint : 'nameExample'. If you go in production this fails and shows a blank page, and you need to changes this nameExample to '/' to show the projectbuild online. But than it shows a blank page in development because it mismatches the name of the project. Hope this will help you.

Related

Missing Script generated by Webpack(development) on first page load

the first time i load the login page the login.js script doesn't load , only the shared.js bundle loads (which has bootstrap js/css and toastr css), if i refresh the page everything loads without problems and after that there are no problems.
Pretty much every time i restart my local server i need refresh the login page to be able to login
my webpack config is as follows
export default {
entry: {
shared: [
'./src/3rdparty/bootstrap/bootstrap.min.js',
'./src/3rdparty/bootstrap/bootstrap.min.css',
'./src/3rdparty/toastr/toastr.min.css',
],
login : {
import: './src/pages/login.js',
filename: 'main/login.js',
dependOn: 'shared',
chunkLoading: false,
}
},
output:{
path: fileURLToPath(new URL('public',import.meta.url)),
clean:true,
},
resolve:{
extensions: ['.js']
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
mode: 'development'
}
The project has been build using Node 16.17 / Expressjs 4
It works without problems if i change the mode to production
Going to write in case i encounter the same issue again:
after adding the compression library i cannot replicate the issue
another issue that i had was that when i was returning messages from the server with the status 400, it would return a invalid string Ex:
{ok:true, description:"username invalid"
always missing the closing bracket }
this issue has also been resolved by using compression middleware

Rollup : single html output

I'm trying to package my Svelte app into a single Html file output.
I've managed to get the desired output with a configuration based on that answer :
Output Single HTML File from Svelte Project
With "npm run dev" everything is fine with the first build, but I'm having issues following (live-reload) builds: bundle['bundle.css'] is not filled in my inlineSvelte's generateBundle function.
I didn't manage to change the rollup-plugin-css-only for rollup-plugin-embed-css, which seemed to have an appropriate name for my needs.
Here's my rollup.config.js :
import svelte from 'rollup-plugin-svelte';
import livereload from 'rollup-plugin-livereload';
import css from 'rollup-plugin-css-only';
...
function inlineSvelte(templatePath, dest) {
return {
name: 'Svelte Inliner',
generateBundle(opts, bundle) {
const file = path.parse(opts.file).base;
const jsCode = bundle[file].code;
const cssCode = bundle['bundle.css'].source;
const template = fs.readFileSync(templatePath, 'utf-8');
bundle[file].code = template
.replace('%%script%%', jsCode)
.replace('%%style%%', cssCode);
}
}
}
export default {
input: 'src/main.js',
output: {
format: 'es',
file: outputDir + 'index.html',
name: 'app'
},
plugins: [
svelte({
compilerOptions: {
dev: !production
}
}),
css({ output: 'bundle.css' }),
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
!production && livereload(outputDir),
inlineSvelte('./src/template.html')
],
watch: {
clearScreen: false
}
};
It is surely possible to embed the produced CSS file in your HTML, at least with some reasonably simple custom plugin.
However, if you only have CSS in your Svelte components, that is you don't have import 'whatever.css' anywhere in your code, you can just rely on Svelte injecting CSS from compiled JS code and be done with it.
This loses a little in terms of performance because such injected CSS will never be cached by the browser, but it avoids the added complexity / risk / coupling associated with a custom build step... And this kind of performance is often not so important in scenarios where you want all your app in a single HTML file.
To enable this, set emitCss: false on the Svelte plugin:
plugins: [
svelte({
emitCss: false,
...
}),
...
],
...
You won't need any Rollup plugin for CSS in this case.

import Stencil in Svelte

I have a Monorepo with a svelte project and a Stencil component library. On the Stencil website they very clearly describe how to integrate the library with, for example, Angular
import { defineCustomElements } from 'test-components/loader';
defineCustomElements(window);
Super easy. But now I would like to use it too in a Svelte project ..... not so super easy anymore :(
When I try to do something similar as described above I get serious errors
fbp/dist is where the Stencil files are.
When I build my Stencil project first and copy my dist into the public folder and load ./dist/fbp.js in the head of index.html it all works. But it would be a lot easier if I could include it similar as it does with Angular. Any suggestions?
Update: Added emitCss which gives
Somewhere at the end it stats: Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
UPDATE: With the fixes of #Sambor, Svelte is now able to download the web component, which unfortunately fails
I have created a new project and I manage to reproduce the same problem.
At first, I was thinking is related to typescript and I've tried bunch of plugins in rollup like : #tscc/rollup-plugin-tscc, rollup-plugin-typescript but it didn't work.
I also tried rollup-plugin-amd with same results...
Then I've tried to change the main output format and use es instead of iife.
This way it also required to change the output to a directory instead of file (because of multiple file generation).
And surprisingly this way it seems to work.
here is my code:
/// index.html
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Test</title>
<link rel='stylesheet' href='build/bundle.css'>
<script type="module" defer src='build/main.js'></script>
</head>
<body>
</body>
</html>
Note: main.js is imported as module.
/// main.js
import App from './App.svelte';
import { applyPolyfills, defineCustomElements } from '../my-comp/loader';
applyPolyfills().then(() => {
defineCustomElements(window);
});
const app = new App({ target: document.body });
export default app;
/// rollup.config
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import postcss from 'rollup-plugin-postcss';
import autoPreprocess from 'svelte-preprocess';
import json from '#rollup/plugin-json';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'es',
name: 'app',
dir: 'public/build'
},
plugins: [
json(),
svelte({
// Enables run-time checks when not in production.
dev: !production,
// Extracts any component CSS out into a separate file — better for performance.
css: css => css.write('public/build/bundle.css'),
// Emit CSS as "files" for other plugins to process
emitCss: true,
preprocess: autoPreprocess()
}),
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')
}),
commonjs(),
postcss({
extract: true,
minimize: true,
use: [
['sass', {
includePaths: ['./node_modules']
}]
]
}),
// In dev mode, call `npm run start` once the bundle has been generated
!production && serve(),
// Watches the `public` directory and refresh the browser on changes when not in production.
!production && livereload('public'),
// Minify for production.
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
Note: I took my config from another svelte project (you can ignore uninteresting plugins)
Now it seems to be working fine, but I think is just the starting point :) because there are some known issues with stencil itself which I come across;
core-3d1820a5.js:97 TypeError: Failed to fetch dynamically imported module: http://localhost:57231/build/my-component.entry.js
core-3d1820a5.js:863 Uncaught (in promise) TypeError: Cannot read property 'isProxied' of undefined
https://github.com/sveltejs/sapper/issues/464
https://github.com/ionic-team/stencil/issues/1981
same with react: Unable to integrate stenciljs component in React application
This is not the completely working solution, but I thought it may help you for the next steps...
I’m still having the same issue in 2020. Surprisingly, the webpack template is working fine. Switching to that for now, until this is resolved.
https://github.com/sveltejs/template-webpack

How do I update file paths in VueJs if I'm using CLI3

I'm a bit lost and need some help with VueJs. I am using Vue CLI3 and have created a new Vue project where eveything is working, no errors in the console etc. However, after running the build task, the copy in my dist folder shows as a blank page. I have learnt that this is to do with needing to update the assetsPublicPath: and remove the '/' forwards slash. To do this I have been told you have to update the config file index.js but there is no such file in my proect? I have also been told there is a config folder, but there isnt?
Therefore how do I update the following
from assetsPublicPath: '/',
to assetsPublicPath: '',
Take a look at the documentation. If you don't have the vue.config.js just create it. I would look something like this:
// vue.config.js
module.exports = {
// Any of the config options will come here. Everything you'll need is in the docs
publicPath: ''
}
Only create a vue.config.js in your project and use inside .File is automatic loaded by vue cli serve. After publish your hosting or server file will must work it.
module.exports = {
css: {
extract: true
},
publicPath: process.env.NODE_ENV === "production" ? "" : "",
outputDir: "dist"
};

sw-precache-webpack-plugin webpack service worker default template

I'm using the sw-precache-webpack-plugin to generate a service worker for my project, I can see all my fonts, js and css files in the cache storage but not the index / html file and its not working when i go offline. I also get a 'site cannot be installed: no matching service worker detected.' when i try and add to homepage on the App manifest.
My stack is a universal React + redux app, with Express + ejs for index file. I'm not sure if its because I'm using ejs rather than a default html file, but it doesnt seem to find the file. Is there a way I can specify a template? My sw-precache-webpack-plugin webpack setting is:
new SWPrecacheWebpackPlugin({
cacheId: 'tester',
filename: 'my-service-worker.js',
directoryIndex: '/',
}),
Any advice would be appreciated
You are missing a specification of a caching strategy in the plugin config.
plugins: [
new SWPrecacheWebpackPlugin({
cacheId: 'tester',
filename: 'my-service-worker.js',
runtimeCaching: [
{
urlPattern: '/',
handler: 'cacheFirst',
}
]
})
]
Documentation: https://github.com/GoogleChrome/sw-precache#runtimecaching-arrayobject

Categories