Using gulp to compile a Vue component without the need for `require` statements

I'm currently exploring the process of constructing a component with Gulp. Right now, I am working on a Vue component that has the following structure:

my-component.vue

<template>
  <div class="foo">
  </div>
</template>

<script>
  export default {
    data() {
      return {};
    },

    props: {
      message: {
        type: String,
        default: ''
      }
    },

    methods: {
      display: function() {
        alert(this.message);
      }
    },
  };
</script>

I am in the process of building this component with the help of Gulp. Here is a snippet from my gulpfile.js:

gulpfile.js

const gulp = require('gulp');
const vueify = require('gulp-vueify2');

gulp.task('default', ['build']);

gulp.task('build', function() {
    return gulp.src('./src/my-component.vue')
        .pipe(vueify())
        .pipe(gulp.dest('./deploy'))
    ;
});

Upon executing the build, I find my-component.js in the "deploy" directory. When I inspect that file, I notice the following at the beginning of my-component.js


var __vueify_style_dispose__ = require("vueify/lib/insert-css")

I am attempting to incorporate the component in an HTML file using the following approach:

<script type="text/javascript" src="./my-component.js"></script>

While the script is successfully loaded, an error appears in the console stating:

Uncaught ReferenceError: require is not defined

How can I construct the component in a way that does not rely on require? Is there a method to achieve this? If so, what is the process?

Answer №1

After searching extensively, I managed to find a solution that doesn't require any additional modules. It's not the most elegant solution, but it gets the job done.

Step 1: Add the following CSS extraction code to your gulpfile.js.

const gulp = require('gulp');
const vueify = require('gulp-vueify2');

gulp.task('default', ['build']);

gulp.task('build', function() {
    return gulp.src('./src/my-component.vue')
        .pipe(vueify({
            extractCSS: true,
            CSSOut: './deploy/bundle.css'
        }))
        .pipe(gulp.dest('./deploy'))
    ;
});

Step 2: Create your component file, my-component.vue.

<template>
  <div class="foo">
      World
  </div>
</template>

<script>
  module.exports = {
      data() {
          return {};
      },

      props: {
          message: {
              type: String,
              default: ''
          }
      }
  };
  // Since you don't have a module, just keep your component somewhere.
  window.vueComponents['my-component'] = module.exports;
</script>

<style>
    .foo {
        color: red;
    }
</style>

Step 3: Update your index.html file.

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="/bundle.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
        <script>
            window.module = {}; // To prevent any errors without a module
            window.vueComponents = {}; // Global registry for your components...
        </script>
        <script src="./my-component.js"></script>
    </head>

    <body>
        <div id="app">
            <div>
                {{ foo }}
                <my-component></my-component>
            </div>
        </div>

        <script>
            new Vue({
                // Assign your components to the Vue instance
                components: window.vueComponents, 
                data() {
                    return {
                        foo: 'Hello'
                    };
                },
                el: '#app'
            });
        </script>
    </body>
</html>

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

npm command syntax to accept multiple arguments

Struggling to pass arguments in an npm command and utilize them in my script For instance: npm run test -b chrome -e QA "scripts": { "test": "something.js ./xyz/abc/cdf --something \"{\\\"browser\\\": \&bsol ...

Find the string "s" within a div element aligned vertically, using Popper

Currently utilizing Popper from Material-UI <Popper id={"simplePopper"} open={true} style={{backgroundColor: 'red',opacity:'0.5',width:'100%',height:'100%'}}> <div style={{height:"100%", ...

Unlock the Power of Rendering MUI Components in ReactJS Using a For Loop

Hey there! Hope everything is going well. I've been working on a fun project creating an Advent/Chocolate Box Calendar using ReactJS. One challenge I'm facing is figuring out how to iterate over a for loop for each day in December and render it ...

Execute AJAX request for two individual buttons

I have a scenario where I want to use two buttons to open separate PHP pages, but I would like to trigger both buttons with a single function. The AJAX function should then determine which button was clicked and open the corresponding PHP page - for exam ...

Unable to assign a value to a null property during the onchange event

I'm currently working on a project where I need to display flight details based on the selected flight number. To achieve this, I have created a dropdown menu that lists all available flight numbers and a table displaying various flight details such a ...

Developing a universal.css and universal.js file for a custom WordPress theme

I have developed a custom WordPress theme with an extensive amount of code. To manage the numerous style and script files, I have segmented them into multiple individual files. To integrate all these files into my template, I utilized the following code w ...

Every time I enter npm start in the terminal, I consistently encounter this error

After developing a simple web app and posting it on my repository, I started encountering these persistent errors. npm ERR! code ELIFECYCLE – David 1 hour ago npm ERR! syscall spawn C:\Windows\system32\cmd.exe;C:\Users'usernam ...

Combining relationships from various models in Laravel to streamline queries

Is it possible to combine two relationships into a single query from two separate models? class User extends Authenticatable { public function relazioneFollower() { return $this->belongsToMany(User::class, 'user_follower','follower ...

Error: Invalid Request - Nodejs Request Method

As part of my project involving payment gateway integration, I needed to make a call to the orders api. However, I encountered an error message: {"error":{"code":"BAD_REQUEST_ERROR","description":"Please provide your api key for authentication purposes."} ...

Verify login availability using Javascript auto-check

For quite some time now, I've been grappling with a significant issue that has been consuming my attention. I am determined to implement an auto-check login availability feature in the registration form of my website. My goal is for it to verify the ...

Issues with vue-router causing improper routing behavior resulting in components not displaying as expected

I am currently using vue-router to display different components for various routes, but unfortunately it doesn't seem to be functioning properly. You can view the compiled program on CodePen here. In my main.js file, I simply define the router and s ...

Tips for efficiently retrieving a record from an array using a JavaScript function

It seems like there might be a simple solution that I'm overlooking, but the code below isn't functioning as expected when the currentRecord is found to be true. How can I efficiently loop through an array and return the record when a match is f ...

What is the purpose of running "npm install" if the "node_modules" directory already exists?

When "npm install" is run on a project directory containing both a "package.json" file and a "node_modules" directory, what impact does it have? Does it replace the current modules with newer versions? Does it update them, or does it have no effect at all ...

What is causing the HTML to PDF generator to create a gap and produce an additional page during printing?

Hey there, I have been experimenting with the html2pdf plugin. The main issue I am facing is that it does not fully utilize the A4 paper size, leaving a gap as seen in the image below. https://i.stack.imgur.com/0AB0W.png Another problem is that it alway ...

Stop and start an Express.js server using the original port number

Currently, my Node.js application utilizes Express.js to handle incoming connections. The code snippet looks something like this: const express = require("express"); var server = express(); server.get("/test", (req, res) => testResponse(req, res)); ser ...

Executing a series of API calls using Rxjs in Angular that result in a null response

I encountered a situation where I needed to make sequential API calls using RxJs in Angular. However, despite successfully implementing the calls, I am struggling with a null error. In this scenario, the second API call depends on receiving an id from the ...

Error handling proves futile as Ajax upload continues to fail

Utilizing a frontend jQuery AJAX script, I am able to successfully transfer images onto a PHP backend script hosted by a Slim framework app. However, there is one specific image (attached) that is causing an issue. When the backend attempts to send back a ...

Thirteen consecutive attempts to fetch information have resulted in failure

I've encountered an issue while attempting to fetch data from my .NET Core 7 API. The error message I'm receiving is as follows: *Unhandled Runtime Error Error: fetch failed Call Stack Object.fetch node:internal/deps/undici/undici (11413:11) pro ...

How can I generate two directory-based slider instances?

Update: Finally, I discovered the root of the problem within my stylesheet. Despite both sliders being loaded, they were overlapping due to their positioning, causing the second slider (or any additional ones) to remain hidden. I've been striving to ...

Javascript is not recognizing if and elseif conditions

I recently developed an IQ Test using JavaScript. I implemented specific conditions for different score ranges, however, the test only displays the IQ score based on the last condition, regardless of the number of correct answers. Despite numerous attempts ...