404 when reloading a Vue website published to Github pages - vue.js

I have deployed the contents of my /dist folder in the master branch of christopherkade.github.io, which has deployed my website succesfully.
But when I navigate using the navbar (christopherkade.com/posts or christopherkade.com/work) and reload the page I get an error by Github pages:
404 File not found
Note that my routing is done using Vue router like so:
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/work',
name: 'Work',
component: Work
},
{
path: '/posts',
name: 'Posts',
component: Posts
},
{ path: '*', component: Home }
]
})
And my project is built like such:
build: {
// Template for index.html
index: path.resolve(__dirname, '../docs/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../docs'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
What could be causing this issue?

But when I navigate using the navbar (christopherkade.com/posts or
christopherkade.com/work) and reload the page 404 File not found
Let me explain why 404 File not found is being shown
When christopherkade.com/posts is triggered from web browser, the machine to which the domain christopherkade.com is mapped is contacted.
The path /posts is searched in its server. in your case, i believe the route for /posts doesn't exist in the server. As the result 404 is displayed
There are few ways to fix this
To prevent the browser from contacting the server when triggering the request christopherkade.com/posts, you can keep mode : 'hash' in your route configuration
How mode : 'hash' works? This is one way to fix your issue
mode : 'hash' makes use of default browser behavior which is to prevent http request from triggering the details that exists after #
As the result, when you trigger christopherkade.com/#/posts , christopherkade.com is being triggered by the browser and once response is received the /posts route from the route config is invoked.
Lets assume that you have control over the server and you are adamant
that you need # to be removed from the URL
Then what you could do is to configure server in such a way that server responds with the same page everytime any paths is being sent. Once response is received in the browser, route will automatically kicked off.
Even in your current program, the routeConfig gets kicked off when you click any links (like work,posts) in your page. This is because the browser behavior is not being invoked at this point.
In your case, you use github for hosting this app with mode: 'history' i myself have to look for a specific solution to workaround this. i will update my answer once i get it.
i hope this was useful.

You can fix this issue by a simple workaround. I combined all the insights from reading multiple issues about this and finally this is what helped me fix this problem.
Solution Logic - You just need a copy of index.html with the name 404.html in the dist folder
Steps to fix
Go to you package.json file, under scripts add a new script called "deploy" like below, you just need to execute this everytime after you build your page. It will automatically take care of the issue.
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"deploy": "cd dist && cp index.html 404.html && cd .. && gh-pages -d dist"
},
This will copy the index.html & rename it 404.html and pushes dist folder under the branch gh-pages and after that your script will appear in the vue ui like below
or
If you are using git subtree push --prefix dist origin gh-pages method to push, then edit the deploy script in package.json to below
"deploy": "cd dist && cp index.html 404.html
and then execute the below git command. PS, don't forget to execute this script before manually using npm script method or from the vue ui
git subtree push --prefix dist origin gh-pages

This actually happens since your browser makes a request to christopherkade.com/posts URL which doesn't exist (this route is defined in Vue application running from index.html).
If you were running your own server, you would probably configure it to render your index.html page for any request URI, so your Vue application would be loaded from any path and handle routing by itself.
Speaking of GitHub pages, you can't just configure them to act the same way I described, but fortunately, there is a workaround which uses custom 404 page:
https://github.com/rafrex/spa-github-pages

As a workaround, I duplicated the index.html and renamed it to 404.html.
In this way, if the page is reloaded, you still get the correct page however this is served through the 404.html file.

As a workaround I have created folders for each route (with a script) and placed the index.html in all of them.
404s still don't work.

If you use Nuxt, this fixes the problem.
layaouts/blank.vue
<template>
<nuxt />
</template>
pages/redirect.vue
<template>
<div></div>
</template>
<script>
export default {
layout: 'blank',
fetch({base, redirect, query}) {
const param = query.p
if (param === undefined) {
return redirect('/')
}
const redirectPath = '/' + param.replace(base, '')
return redirect(redirectPath)
}
}
</script>
static/404.html
<html>
<head>
<script>
var pathName = window.location.pathname;
var redirectPath = '/<repository-name>/redirect';
location.href = redirectPath + '?p=' + encodeURI(pathName);
</script>
</head>
</html>
https://gist.github.com/orimajp/2541a8cde9abf3a925dffd052ced9008

Very simple perfect solution just follow the below instruction
Add a _redirects file inside the /public folder like /public/_redirects
After that add /* /index.html 200 into the _redirects file
I think with this solution your redirect problem will be solved

Related

Vue js how to use route from index.html to docs folder

I am new to Vue js, I am building a website using Vue js where I have a home page and docs folder which contains a lot of documents written and save in a .md file.
Now How I can on the navbar click redirect from my route.js page to docs .md files. Below is my folder structure.
I want to serve my homepage from main.js which is created using vue.js, and docs folder containing markdown files. Inside the docs folder have .vuepress with config.js which was configured to load index.md as the home page.
- docs
- guide
- index.md
- src
- components
- route.js
- vue.config.js
- main.js
Package.json
{
"scripts": {
"docs:build": "vuepress build docs",
"docs:dev": "vuepress dev docs",
"dev": "vuepress dev docs",
"build": "vuepress build docs",
"start": "vue-cli-service serve"
},
}
UPDATE: There are a few issues in your new code:
The app site uses Vue 2, which requires VuePress 1.x, but you have VuePress 2.x installed. If you want the docs and app source in the same project root with different NPM dependencies, you'd need something like a monorepo. To otherwise share NPM dependencies, you'll have to upgrade your app project to Vue 3 or downgrade VuePress. For the sake of example, install VuePress 1.x instead:
npm i -D vuepress#1
The VuePress port is not configured, so it starts at 8080 (until a free port is found). The docs link in your app is hard-coded to port 3000, so your VuePress should be configured to start there:
// docs/.vuepress/config.js
module.exports = {
port: 3000
}
The VuePress base URL is not configured, while your app assumes a base of /docs. Update your VuePress config to set the base URL acccordingly:
// docs/.vuepress/config.js
module.exports = {
base: '/docs/'
}
See GitHub PR
Answer to original question:
VuePress setup
Install vuepress in your project:
$ npm i -D vuepress # if using #vue/cli#4
$ npm i -D vuepress#next # if using #vue/cli#5
Add NPM scripts for Vuepress:
// package.json
{
"scripts": {
"docs:build": "vuepress build docs",
"docs:dev": "vuepress dev docs"
}
}
Create docs/.vuepress/config.js, and export a config object:
a. dest - Output the docs to your app's build output directory (dist for Vue CLI scaffolded projects).
b. base - Set the base URL so that it matches the intended destination on the server (e.g., set base URL to docs if deploying docs to https://example.com/docs/).
c. port - Set the port of the VuePress dev server (we'll configure Vue CLI's dev server to point there later).
d. themeConfig.nav - Set the top navbar links.
// docs/.vuepress/config.js
module.exports = {
dest: 'dist/docs',
title: 'My Project Docs',
base: '/docs/',
port: 3000,
themeConfig: {
nav: [
{
text: 'Guide',
link: '/guide/',
},
{
text: 'Main Project',
link: 'http://localhost:8080'
}
],
}
}
Add a docs link to your app's navbar (e.g., in App.vue):
<nav>
Docs 👈
<router-link to="/">Home</router-link>
...
</nav>
Create docs/README.md with the following contents:
# Hello World
Building
Build your app before the docs (especially if the app's build command deletes the output directory beforehand, as it does with Vue CLI):
$ npm run build
$ npm run docs:build
Development
If using Vue CLI, configure the dev server to redirect /docs to the VuePress dev server:
Configure Vue CLI's devServer.before:
// vue.config.js
module.exports = {
devServer: {
before: app => {
// point `/docs` to VuePress dev server, configured above
app.get('/docs', (req, res) => {
res.redirect('http://localhost:3000/docs')
})
}
}
}
Start the app's server and the docs server:
$ npm run serve
$ npm run docs:dev
You could add the the docs folder into the public directory, then link to /docs/guide/...

Vue CLI deploy to a subfolder using relative paths

Using Vue CLI, and Vue 2.
Anyone knows how to build the project using relative paths, so I can place it in any subfolder in my server and it will work? (for example www.mysite.com/subfolder/)
I've tried with
// vue.config.js
module.exports = {
publicPath: "",
};
And it builds the paths relative (ie, js/app.js instead of /js/app.js), but the app wont' load. Nothing shows on the page.
Strangest thing is that all files are loaded correctly (I can check on network tab in Chrome devtools), no JS errors, etc. So the page is loading all the files but it seems like it's refusing to mount the app when using relative paths.
I know that I can add the absolute path to the build process but that's not what I need. My client needs to be able to move the files freely from one subfolder to another and the app should work without the need to recompile
PS: Also tried building the project with Vite and Vue 3, same problem.
Thanks!
Alright, looks like all that's needed is:
build with a relative publicPath (empty string)
// vue.config.js
module.exports = {
publicPath: "",
};
add a <base> tag to the final HTML...
<base href="/subfolder/" />
For Vite, the export should be
// vite.config.js
export default {
...
base: "",
};

How to uglify a js file upon building the vue project

I have a VUE2 project and in the public folder I created an iframe.html file that will be loaded in an iframe.
That iframe will also load a javascript.js file that I want encoded/uglified upon "npm run build" but I also want to be able to access it during dev.
How could I proceed?
Should this js file be placed inside the /src/assets/ folder and referenced from the iframe.html file? If yes, any advice?
Or should it stay in the public folder and upod the dist folder being built, encode it with something.
Any solution is welcome, thanks in advance!
Edit: Here are further details of how I use the iframe.
First, I'm referencing the .vue file in the router like so:
{
path: "/pages/:id/edit",
name: "edit",
component: () => import("../views/Edit.vue"),
},
Next, in the Edit.vue file, I add the iframe like so (note how it's referencing iframe.html that is in the public directory):
<iframe
id="iframe"
ref="iframe"
src="iframe.html"
/>
Next, in the iframe.html it's just normal html code, with this part including the javascript.js file (that actually is in the public folder as well for now)
<script src="javascript.js"></script>
You can explicitly include the .js file in your Webpack config by adding a rule for UglifyJsPlugin:
npm i -D uglifyjs-webpack-plugin
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
...
module.exports = {
optimization: {
minimizer: [
new UglifyJsPlugin({
include: /\/regex-for-file/,
minimize: true
})
]
}
...
};
In Vue.config.js, this might look like:
configureWebpack: {
plugins : [
new webpack.optimize.UglifyJsPlugin({
uglifyOptions: {
include: /\/regex-for-file/,
minimize: true
}
)}
]
}
Another option is to use uglify-es; this would allow you to get even more explicit by specifying from where to copy the file during build (assuming you might want the file located outside of src/):
npm i -D uglify-es // CopyWebpackPlugin ships w/ Vue's Webpack conf by default
const UglifyJS = require('uglify-es');
const { resolve } = require('path');
const resolveAbs = (dir) => resolve(__dirname, dir);
new CopyWebpackPlugin([
{
from: resolveAbs('../external'),
to: config.build.assetsSubDirectory
},
{
from: resolveAbs('../src/custom-build-path'),
to: config.build.assetsServerDirectory,
transform: (content, path) => UglifyJS.minify(content.toString()).code;
}
]),
To be able to access it during dev, you can include the path of the js file (relative to your Vue src directory) using the resolve.alias option in the config (so you don't need to deal with possibly ridiculous relative paths in your project). Finally, you can look into webpack's HTML plugin docs for info on importing an external index.html file if needed
I would recommend not putting it in static; by default it will not be minified and built if placed in that directory.
Update/edit: Sorry, I saw a 'uglify' and just assumed you wanted uglify js. As long as the script is in your Vue project directory (or otherwise specified in the Webpack config) the file should be minified during build. Vue has pretty smart defaults for Webpack; assuming the iframe is being referenced somewhere in the app i.e. the dependency graph it will be built.

Vue Router’s paths to assets break on reload

I'm working with Webpack 4.43, Vue 2.6.11 & Vue Router 3.1.6
Webpack generates a dist folder with a bundle.js and an index.html.
If I navigate to nested pages through the app links everything works fine, but if I try to reload a nested page, the index.html can't load bundle.js because it tries to find it at the nested page level. For example if I go to localhost:8080/fr/contact it will try to load localhost:8080/fr/bundle.js
I've seen many other related topic but no one ever gives a real answer. Does anyone have a solution?
EDIT: Don't know if it helps, but I just realized that the images don't load in nested pages even when I reach them through the router-links. Same problem: it looks for localhost:8080/fr/my-image.png instead of localhost:8080/my-image.png
Finally solved it by setting publicPath: '/' in my Webpack config (not the Vue config). Here's how it looks:
module.exports = {
...
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
...
}

Vue Cli 3 Generated Project Set HTML Title

Currently, after generating a project with Vue CLI 3 the title is "Vue App".
If I set the title in the created hook via document.title the browser will still will flash "Vue App" prior to displaying the title set via document.title.
Looking for a way to set the HTML title for a Vue CLI 3 generated project without it flashing the default "Vue App" title first.
You can set the title in /public/index.html statically.
Setting it to an empty string in index.html and keeping the update in the hook gets rid of the flashing.
also You can use custom index.html in another way, modify your vue.config.js:
module.exports = {
publicPath: '/',
chainWebpack: config => {
config
.plugin("html")
.tap(args => {
args[0].template = './public/index.html'
return args
})
}
};
You can add postinstall to scripts section in your package.json with next command:
"postinstall": "cp ./public/index.html ./node_modules/#vue/cli-service/lib/config/index-default.html"