The Vue component fails to render and the DevTools are experiencing a hang-up

I'm sorry for the confusing title, but I am currently puzzled by a situation related to how Express serves static files. I am working on a simple Vue app that is being served statically by Express.

server/app.js (entry point)

import express from 'express';
import morgan from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';

const app = express();

// Serving static files from the public directory
app.use(express.static(path.join(__dirname, '..', 'public')));

// Using morgan to log requests in dev mode
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true,
}));

app.listen(process.env.PORT || 3000, () => {
    console.log(`Listening on port: ${process.env.PORT}`);
});

// Serving index.html page when root request is made
app.get('/', (req, res, next) => {
    res.sendFile('index.html', {
        root: path.join(__dirname, '..', 'public'),
    });
});

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Hello World</title>
    </head>
    <body>
        <div id="app"></div>
    </body>
</html>

public/main.js

import Vue from 'vue';
import BootstrapVue from 'bootstrap-vue';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-vue/dist/bootstrap-vue.css';

import App from './App';

Vue.use(BootstrapVue);
Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
    el: '#app',
    components: { App },
    template: '<App/>',
});

public/App.vue

<template>
    Hello World!
</template>

<script>
    export default {
        name: 'App',
    };
</script>

<style>
    #app {}
</style>

When I serve the files from the public directory, I am able to access them in the browser at URLs like http://localhost:3000/App.vue.

This setup should display a simple UI page with just the text "Hello World!" In Chrome, however, I only see a blank page with the title "Hello World" and cannot open DevTools. The Vue extension also does not detect Vue running on the page.

In Mozilla, the same issue occurs as in Chrome, but I can view DevTools and only see basic HTML without any other files being loaded, even if they are present in the public directory. There are no errors in the logs either.

While initially hitting the root endpoint used to produce a response in the server logs, it no longer does so for some reason.

I have attempted to use a basic webpack.config to bundle my Vue and JS files, but the behavior remains the same.

Answer №1

Your current project setup would benefit from a bundler like Webpack. As noted in the feedback, this is not something that can be easily added later on.

Initially, individual .vue components need to be compiled. Browsers are unable to understand this format by default. Typically, a loader accomplishes this task (refer to https://github.com/vuejs/vue-loader).

Furthermore, browsers do not typically support module imports (although this is evolving), necessitating a solution to convert these import statements into a bundle of scripts that can function within your HTML document.

I strongly recommend initiating your project through the vue-cli tools. Check out https://github.com/vuejs/vue-cli.


You can integrate Vue into your HTML page by:

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

However, this will significantly alter how your source code is structured, potentially hindering the use of certain third-party resources unless they also endorse typical <script> tag implementation. You'll have to generate components utilizing the Vue.component() syntax.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can the "el" attribute be used to locate a specific Vue component?

If I were to have a component like this: <b-select id="selectfield" :src="['a', 'b']"></b-select> It will display as follows: <select id="selectfield"> <option value="a">a</option> <option val ...

As I enlarge the font size, the border around the div also expands

Can someone explain why the size of the div border increases along with the font size? If you'd like to see an example, check out this link to a jsFiddle: LINK TO JS FIDDLE: http://jsfiddle.net/krishna22211/m14qms52 ...

error caused by returning a value in NodeJS that creates a circular structure

I'm in need of some assistance with configuring my REST routes in Node and Express. Here's the issue I'm facing: In my controller.js file: module.exports = { findAll: function(req, res) { var users = User.findAll(); res.json(use ...

Error message displayed: MUI Textfield does not support input of decimal values

I have a textfield where users can enter the unit price const [unitPrice, setUnitPrice] = useState(0); <TextField label="Unit Price" variant="outlined" margin="normal" value={unitPrice.toString ...

Unavailable dates on Datepicker (information fetched from the database)

I am currently working on extracting dates from my database and storing them in an array as json data. In my MAIN.PHP file: $('#datepicker').focus(function(){ $.ajax({ url: 'getDates.p ...

Resolving Unrecognized Vue Variable in PhpStorm

I'm encountering an issue with my Vue script in PhpStorm. Despite setting the variable redirect_to, I am getting an Unresolved variable syntax error during debugging. Please refer to the image below for further information. How can I resolve this prob ...

VueJS can manipulate an inline template by dynamically changing its content and reinitializing

this particular query shares similarities with the discussions on VueJS re-compiling HTML in an inline-template component as well as How to implement Vue js directive in an appended html element Regrettably, the approach suggested in those threads is no l ...

What is the procedure for closing a snackbar when the close button is clicked?

I am having trouble closing a snackbar when the close button is clicked. The snackbar should initially pop up on page load and only close when manually triggered. I have set the timeout to zero, but the snackbar does not close when the close button is clic ...

Is there a way to attach a model to an Angular directive?

Currently, I am implementing angular's typeahead functionality using the following resource: I have created a directive with the following template: <div> <input type="text" ng-model="user.selected" placeholder="Ty ...

What steps are necessary to activate javascript in HTML for WebView?

I recently discovered that when my HTML/JavaScript site is visited via an Android webview, JavaScript is disabled by default. This causes a pricing list on my page to not display properly because it requires a JavaScript class to be added for it to open. I ...

Having trouble downloading the compression webpack plugin using npm, as it keeps throwing an error

Hey there, this message pops up when attempting to execute the following command: npm install compression-webpack-plugin Here is the accompanying error: `PS D:\phaser games\game-slot-machine> npm install compression-webpack-plugin npm ERR! ...

Issue with import alias not functioning within route grouping in Nextjs

Exploring the use of route groups and nested layout files led to encountering a "module-not-found" error with every import that used "@". Here is my jsconfig.json setup: { "compilerOptions": { "baseUrl": "./src", &q ...

Error happening outside of controllers or services but not being recorded

I've encountered an issue where exceptions occurring outside of controllers or services in plain JavaScript code are not being reported, do not appear in the console, and cannot be handled. For example, if there is an exception within a Car class that ...

I am interested in generating a Stacked Chart in Google Charts using data from a JSON file

Hey there, I'm looking to generate a stacked chart using JSON data in Google Charts. My current challenge revolves around the code snippet var data = google.visualization.arrayToDataTable([. <?php $tmp = array(); require "configdashboard.php"; /* ...

What are some ways I can utilize session and cookies for express when using express.static('static')?

Exploring the realm of session cookies in web development, specifically with an Express backend and a Vue PWA/SPA mounted on static files via express.use(express.static('static'));. Through some research, I discovered that we can include options ...

Strategies for evaluating a Promise-returning imported function in Jest

I am currently facing an issue with a simple function that I need to write a test for in order to meet the coverage threshold. import { lambdaPromise } from '@helpers'; export const main = async event => lambdaPromise(event, findUsers); The ...

How to utilize the index in a foreach loop as a variable in JavaScript

I am facing an issue with using the index of a forEach loop to access an array index in my code. It seems to work when I use a number directly, but not when I try to use the index variable. Any suggestions or insights on how to resolve this? let post ...

Strengthening Security with Node and Express JS to Combat Brute Force Attacks

When creating a website with Node and Express JS, I want to restrict invalid login attempts for security reasons. This will not only help prevent online hacking but also decrease the number of unnecessary database queries. Can anyone suggest some methods ...

What is the method to generate an array of values using a single attribute in GeoJSON data?

Note: After reviewing some possible solutions mentioned in this thread, I found that .map is the perfect fit for what I need, which was not covered in the original post. Thomas's response below addresses my specific requirement. In JavaScript, how ca ...

Stop Element-UI from automatically applying the list-item style to li elements

I have a list of data elements that I am rendering in the following way: <ul> <li v-for="el in elements"> {{el.data}} </li> </ul> Here's how I style it in my .css file: ul { list-style-type: none; padd ...