Incorporating Vue into a dated website by eliminating the div and replacing it with new dynamic Vue components

As I attempt to integrate Vue into my old website, I want the existing jQuery scripts to continue functioning and the old HTML content to be displayed. However, I am encountering an issue where the el element and its contents are being removed.

This problem arises specifically when using the webpacked version of the script. For example:

<html>
    <head></head>
    <body>
        <div id="wrapper">
            <p>dsadfasfasfasfas</p>
            <p>dfasdsadasdasdas</p>
        </div>
    </body>
    <script src="/assets/js/app.min.js"></script>
</html>

Everything within the body tag fails to display in this scenario. However, if I import Vue and use the following code instead of the webpacked version, everything functions properly:

window.app = new Vue({
    el: '#wrapper',
    data: {
        test: 'hello world'
    },
    created() {
        console.log('Vue Running');
    }
});

Edit

Here is the content of app.js that gets compiled:

import Vue from 'vue';

// window.EventBus = new Vue();
window.app = new Vue({
    el: '#wrapper',
    data: {
        test: 'hello world'
    },
    created() {
        console.log('Vue Running');
    }
});

Edit

Below is the configuration in my webpack.config.js:

const path = require('path');
module.exports = {
    mode: 'production',
    entry: [
        './resources/js/vue/app.js'
    ],
    output: {
        filename: 'app.min.js',
        path: path.resolve(__dirname, 'public_html/assets/js/vue')
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                use: 'vue-loader'
            }
        ]
    },
    plugins: [
        new VueLoaderPlugin()
    ]
};

Edit 2

I tried removing the import vue from 'vue', and imported it using a standard script src=... method, which solved the issue. I assumed that importing and compiling Vue would automatically include it on my website.

Answer №1

It appears that your Webpack configuration is missing some necessary components.

If you were to check the browser console, you would notice the following message:

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

The HTML within the element #wrapper is formatted as a template, but Vue cannot compile and utilize it due to the fact that your build only includes the runtime version of Vue.

To rectify this issue, simply include the following in your webpack.config.js:

resolve: {
  alias: {
    'vue$': 'vue/dist/vue.esm.js'
  },
},

This adjustment will bring in the Vue runtime along with the compiler for proper functionality.

Answer №2

When exporting the NPM package, keep in mind that the default build is the runtime-only version without the template compiler. To overcome this, you can either import the full build of Vue in your JavaScript file or set up a webpack alias.

If you define templates using the render function or Single File Component, you won't encounter this issue.

Remember:

If you don't need to support older browsers or use the latest ES features, you can skip using `babel-loader`. Similarly, if you're not utilizing Single File Components, there's no need for `vue-loader`.

Additionally, ensure that you include the meta tag in your HTML like so: <meta charset="utf-8">

To make it work, follow this configuration -

// webpack
module.exports = {
  mode: "production",
  entry: ["./app.js"],
  output: { filename: "./app.min.js" },
  resolve: { alias: { vue: "vue/dist/vue.js" } },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: "babel-loader"
      },
      {
        test: /\.vue$/,
        use: "vue-loader"
      }
    ]
  }
};
// app.js

import Vue from "vue";

// Alternatively, import Vue from 'vue/dist/vue.js'; if you prefer not to use webpack alias

window.app = new Vue({
  el: "#app",
  data: { message: "Hello Vue!" },
  created() {
    console.log("<><><> Vue Created");
  }
});

<!-- index.html -->

<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<div id="app">
    <p>{{message}}</p>
</div>
<script src="app.min.js"></script>
</body>
</html>

Answer №3

Hey there,

Everything seems fine because your compiled code appears like this:

import Vue from 'vue';

// window.EventBus = new Vue();
window.app = new Vue({
    el: '#wrapper',
    data: {
        test: 'hello world'
    },
    created() {
        console.log('Vue Running');
    }
});

But how does the browser know how to import 'vue'?

Your compiled version is not quite ready for the browser, I suspect there might be an issue with your build configuration

Could you share it with us?

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

The constructor window.CCapture is not valid in Node.js environment

Can anyone help me figure out how to load CCapture in Node.js without using a headless browser for recording canvas stream? Every time I try, I keep running into the error message saying "window.CCapture is not a constructor." If you are familiar with the ...

How can I extract the selected sorting parameters in Vuetify datatables?

Currently, I am developing an export tool specifically for a Vuetify datatable. One of the key requirements is to pass on to the generator the columns by which the datatable has been sorted along with their respective directions. I have been searching fo ...

Is it possible to develop an image that can be zoomed in and out using the mouse

$(document.createElement('img')) .width(imgW) .height(imgH) .addClass('img_full') .attr('src', $(this).attr('data-src')) .draggable() .css({ &a ...

What is the best method for showcasing a nested JSON value?

I need to show the data for the month of April. Here is the code snippet: {{my_dates['2018-04-23']}} This code displays: { "april":0, "may":0, "june":0, "july":0, "august":0, "september":0, "october":0, "income_trips":" ...

Is it possible to design a Typescript type that only contains one property from a defined set and is indexable by that set as well?

I have the different types listed below: type OrBranch = { or: Branch[] } type AndBranch = { and: Branch[] } I need a type called Branch that can either be an OrBranch or an AndBranch. I initially attempted this: type Branch = AndBrand | OrBranch ...

Sending values from multiple radio groups in JavaScript can be done by accessing each group individually and extracting

This is an add to cart system. Currently, I am able to send quantity with an ID. However, I also want to send radio group values. How can I achieve this? Here are my codes: product.php <script> jQuery(function ($) { $('.popbutton').on(&a ...

jQuery causing trouble with AJAX in Rails

Currently, I am fetching a list of users from the controller side and generating the HTML code to append it. This is how I wrote the code: $.ajax({ type : "get", contentType : "application/json; charset=utf-8", url : "/users/sear ...

Guide to adjusting the color of Fluent UI icon when hovering with mouse?

I've been implementing Fluent UI in my current project. When initializing my button, I use this straightforward JavaScript code: iconProps: { iconName: 'NewFolder', styles: { root: { color: 'orang ...

The Next.js build version encounters an issue with 'auth' property being undefined and causes a failure

Our team has been happily working on a Next.js based website for the past few months. Everything was running smoothly without any major issues until yesterday when we encountered an error on the production version while using router.push: Cannot read prope ...

Node.js scheduler library for triggering events based on time in a cron-like fashion

Currently, I am utilizing Node.js to develop a web application. My aim is to trigger events at specific times. While I am aware of using setTimeout and computing the time difference from the present moment, this method does not account for various timezone ...

The functionality of the button is disabled once a pop-up JavaScript is implemented

I have encountered an issue with my HTML code that involves a button intended to hide certain content. The problem arose when I implemented a popup feature, causing the button to malfunction. Here is the JavaScript for the popup: $ = function(id) { retur ...

Could not find yarn command even after installation with npm

Following the guidelines for yarn v2 installation, I tried to install using npm install -g yarn. I executed sudo npm install -g yarn on Ubuntu 20.04. However, after running this command, it returned "command not found." ❯ sudo npm install -g yarn > ...

Using jQuery to adjust the length of a string to fit within a specific width

I am working with a table and need to input strings in each cell, but they are wider than the cell width. I want to shorten the strings without breaking lines, and add '...' at the end to show that the string is long. The table consists of aroun ...

Is there a way for app.use to identify and match requests that begin with the same path?

Given that app.use() responds to any path that starts with /, why does the request localhost:3000/foo match the second method instead of the first? app.use("/",express.static('public'), function(req,res,next) { console.log(& ...

Following a POST request, the redirection functionality in Next.js seems to be malfunctioning

I am facing an issue with redirecting the user after submitting a form. I have a button that triggers a post request to my API route, which then inserts a row in the database. The goal is to redirect the user to / once everything is done. However, the retu ...

Accessing the property of the scrollbox in Reactjs: How to get the horizontal offset

I am currently working on a scroll view designed as a series of views wrapped horizontally within a container. <div id="scroller" ref="scroller" onClick= {this.onClick.bind(this)} onMouseMove={this._onMouseMove.bind(this)}> {t ...

Dropzone failing to verify the maximum file limit

I am currently using dropzone to upload files on my website. I have limited the number of files that can be uploaded to a maximum of six. The code works perfectly when uploading one image at a time, but if I select more than six images by holding down the ...

Unit Testing with Jest: Testing the Invocation of a Function within a Nested (Asynchronous) Function

Attempting to create a unit test for a nested function, here is the structure: myFunction.js const anotherFunction = require('./anotherFunction.js') module.exports = (app, io) => { return (req, res) => { const { id, value } = req.q ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

Adjust the position if the height exceeds 100 pixels

Can someone help with this code issue? $(document).ready(function () { if ($('.pi-img').height() > 100) { $(this).css('top' , '30%'); console.log('yeah'); } }); I am encountering difficu ...