How to properly set up Vite, Express, Tailwind web app - express

Scenario:
I am making a basic web app using Vite & Tailwind. I set up my app as normal installing Vite, and Tailwind, and got everything running fine by testing for Tailwind css on localhost:5500.
Problem:
Once I added an Express server to the mix, and it sends the index.html in response to a 'GET' request # '/', I no longer get the compiled CSS from tailwind.
Is this an uncommon setup that should be troublesome?

You could possibly use a middleware like express.static
Example:
const express = require('express')
const app = express()
app.use(express.static(__dirname + '/public'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
In this example, the express.static middleware is used to serve the public directory, which is where the compiled CSS files from Tailwind will be located. Then the express server will send the index.html file in response to a GET request at the root '/' path.
Extra: Alternatively you can also use Webpack or Parcel , which can automatically handle the process of bundling and serving your CSS files

Related

How to use node server with Vue Vite bundler

Does someone know how to use Nodejs server instead of Vite own frontend dev server on the port 3000. I tried all command combinations like those below but with no success
vite
vite preview
vite preview --port:5000
Thanks
UPDATE Feb 8-th 2022
I have found a way. We have to add flag --watch to the vite build command, like: vite build --watch That way Vite will bundle only changes to the front-end and store it in the /dist folder but it will watch outside server like Nodejs. That way we can develop both front and back end file simultaneously and see the result immediately. We have to launch server file separately and serve index.html from there. If we use Nodejs and Express on the server side we also have to point default directory to be /dist because Vite will put bundled files there, like app.use(express.static(__dirname + '/dist'));. node will automatically serve index.html and other bundled files from this folder.
Basically you will set the middlewareMode to ssr on the server options:
const fs = require('fs')
const path = require('path')
const express = require('express')
const { createServer: createViteServer } = require('vite')
async function createServer() {
const app = express()
// Create Vite server in middleware mode. This disables Vite's own HTML
// serving logic and let the parent server take control.
//
// If you want to use Vite's own HTML serving logic (using Vite as
// a development middleware), using 'html' instead.
const vite = await createViteServer({
server: { middlewareMode: 'ssr' }
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
app.use('*', async (req, res) => {
// serve index.html - we will tackle this next
})
app.listen(3000)
}
createServer()
This is explained in the doc: https://vitejs.dev/guide/ssr.html#setting-up-the-dev-server
Update for Vite 2.x
For Vite 2.x set server.middlewareMode to true and appType to custom:
// ...
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'custom'
})

Built Vue SPA not working when using "publicPath"

I set a public path in vue.config.js like
module.exports = {
publicPath: '/subpath'
};
it works fine when I start the devlopment server with npm run serve (vue-cli-service serve). The app becomes available at localhost:8080/subpath which is exactly what I want. It uses vue-router and at least in development it seems to work perfekt with the /subpath as publicPath.
Problem
I am using Express to serve the app files. Running npm run build the app will be built and stored to ./dist folder (default output folder).
// simplified server.js
app.use(express.static(path.join(__dirname, '/dist')));
app.get('/', (req, res, next) => {
res.sendfile('./dist/index.html');
});
After starting my express server and visiting my browser at localhost:<port>/subpath or localhost:<port> it can't find the necessary files.
// EXAMPLE FROM BROWSER CONSOLE
GET http://localhost:5050/subpath/js/app.6c6daa90.js net::ERR_ABORTED 404 (Not Found)
Which somehow looks obvious to me but I don't know how to set the express server correctly to respect the publicPath setting . Maybe there is a different approach ?
Attempt #1
I made a little change in my express server.js
// app.use(express.static(path.join(__dirname, '/dist')));
/* NEW */
app.use('/subpath', express.static(path.join(__dirname, '/dist')));
This way it should serve the static files from the /dist folder when requested with /subpath/app.js
Result
From Browser console when requesting localhost:<port>/subpath or localhost:<port>
Refused to load the font 'data:application/font-woff2;base64,<omitted>' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.
Refused to load the image 'http://localhost:5050/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
I played around with express.static and this combination seems to work for me
const path = require('path');
const express = require('express');
const history = require('connect-history-api-fallback');
const app = express();
app.use(history());
app.use(express.static(path.join(__dirname, '/dist')));
app.use('/subpath', express.static(path.join(__dirname, '/dist')));
const listener = app.listen(5050, () => {
console.log(`Open http://localhost:${port} in your browser`);
});
Sidenote : Adding connect-history-api-fallback was not required to solve the initial problem but is required for vue-router to work properly when in history mode.

Serving static files from an express/node.js application

Hi I am a newbie and started to learn about node recently. I took an Heroku tutorial on websockets (https://devcenter.heroku.com/articles/node-websockets) and adapted it for a specific project I was working on. In the example code there was a single index.html file with some embedded javascript. I moved this script out to a separate file and referenced it in the HTML. Everything worked fine locally but doesn't work when i deploy to Heroko. I chatted with the very helpful team at Heroku who informed me that my server side code is serving up all files as HTML and I need to change the code. They gave me some pointers and I tried as many things as I could over several days but to no avail. In the end they recommended coming to this forum as a way to solve the problem as it is beyond their scope. The existing code that serves up the index.html file is as follows:
const express = require('express');
const SocketServer = require('ws').Server;
const path = require('path');
const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');
const server = express()
.use((req, res) => res.sendFile(INDEX) )
.listen(PORT, () => console.log(Listening on ${ PORT }));
At first i edited this to include the line:
app.use(express.static('public'))
but this didn't work. I then amended as follows and it still doesn't work:
const INDEX = path.join(__dirname, 'index.html');
const JS = path.join(__dirname, 'client.js');
const server = express()
.use((req, res) => {
res.sendFile(INDEX);
res.sendFile(JS);
I have looked at other tutorials that work when i run them in isolation but when I try to adapt my above code it simply doesn't work. I would really appreciate if someone out there could point me in the right direction.
BTW this is what Heroku told me:
"To explain a bit further this error Uncaught SyntaxError: Unexpected token < is because the URL for http://thawing-journey-33085.herokuapp.com/client.js isn't serving a javascript file but is instead trying to serve the HTML for the homepage. This suggests you have an issue with the routing in your application which you'll need to review. This is probably because your server.js file doesn't check for any particular URL before sending the index.html file."
Thanks
I serve my static files like this:
// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, '../public')));
// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, '../public', 'index.html'));
});
This way i set the static folder in the express.static middleware so i can serve the files. And then i redirect all url request to the index.html
To know more: express static

Ember app served from express urls don't work after refresh

In ember I build for production into the /client folder in my express app. In express at the bottom just before I start the app I have these lines
var api = require('./app/routes/api');
app.use('/api/v'+apiVersion, api);
app.use(express.static(__dirname + '/client'));
That works up until I refresh the page at which point it returns a Cannot GET for that route, in my logs from morgan in the terminal I see it's making a call to /url_here instead of routing to the index.html file and allowing ember to take over from there. Do I need to set this up a different way?
Your express app need to handle 404 error and send 'index.html' of client app.
Add this code at the very bottom (below all others):
app.use('/assets', express.static(__dirname + '/client/assets'));
app.use(function(req, res, next) {
res.sendfile(__dirname + '/client/index.html');
});

How to Serve Static Content (.html, .js, etc) with Express.JS

Express isn't letting my web application load up AngularJS. My web application has a directory structure that basically looks like this:
\root
server.js
\angularApplication
index.html
\assets
angular.js
My server.js looks like this:
var express = require('express');
var app = express();
app.get("/", function(req, res) {
res.sendFile(__dirname + '/angularApplication/index.html');
});
app.use("/angularScripts", express.static(__dirname + '/angularApplication/assets'));
index.html loads fine, but the script doesn't load. I get this 404 error:
GET http://localhost:8000/angularScripts/angular.js
If I reference AngularJS in my HTML normally:
<script src="/relative-path-to/angular.js"></script>
then Express still won't get the files. What am I doing incorrectly, and why does Express refuse to serve up any my scripts?
The following worked for me:
app.use("/angularJS", express.static(__dirname + '/angularApplication/assets'));
But only if I reference the script in the HTML like this:
<script src="angularJS/angular.js"></script>
Obviously this isn't how app.use is meant to be used. The better solution I've found is this:
app.use(express.static(__dirname + '/angularApplication/assets'));
// app.use(express.static(__dirname + '/angularApplication/etc'));
These will serve up all of the files in the directory, and thus the scripts and stylesheets can be referenced like this instead on the front-end:
<script src="angular.js"></script>