Had an issue with Unexpected token error while bundling a Vue component with Rollup, using the commonjs plugin

When trying to package a Vue component using rollup, an error about an unexpected token from the commonjs plugin keeps popping up:

(plugin commonjs) SyntaxError: Unexpected token https://i.sstatic.net/kJrp3.png

Here is a snippet from the rollup.config.js file:

import peerDepsExternal from "rollup-plugin-peer-deps-external";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "rollup-plugin-typescript2";
import vue from "rollup-plugin-vue";
import {babel} from '@rollup/plugin-babel';

import packageJson from "./package.json";

export default {
    input: "src/index.ts",
    output: [
        {
            format: "cjs",
            file: packageJson.main,
            sourcemap: true
        },
        {
            format: "esm",
            file: packageJson.module,
            sourcemap: true
        }
    ],
    plugins: [babel(), peerDepsExternal(), resolve(), commonjs(), typescript(), vue()]
};

Also, here's a snippet from the button.vue file:

<template>
  <button>button</button>
</template>
<script lang="ts">
</script>

Looking for a solution? Well, here's something I discovered:

A more effective way might be to utilize vue-sfc-rollup when packaging Vue components.

Update 2023: These days, Vite has gained popularity and you can leverage Vite Lib mode for packaging Vue components intended for NPM. Check out this starter template that could be of assistance.

Answer №1

I encountered a similar issue where I was frustrated with a particular html tag within the <template>.

plugins: [
  vue() //make sure this is the first one
  babel(),
  peerDepsExternal(),
  resolve(),
  commonjs(),
  typescript(),
],

Check out this problem.

Answer №2

The main goal of the commonjs plugin is to transform CommonJS modules into ES6 modules, as mentioned in the documentation. If you are already using ESM (ECMAScript Modules) in your source code, there is no need to transpile your code with the commonjs plugin. The exclude option can help achieve this.

For example:

plugins: [
  // some plugins here
  commonjs({
    exclude: 'src/**',
  }),
  // other plugins here
],

Additionally, it is important to note that the babel plugin should come after the commonjs plugin in the plugins array, as indicated in the documentation:

When using @rollup/plugin-babel along with @rollup/plugin-commonjs within the same Rollup configuration, make sure that @rollup/plugin-commonjs precedes the @rollup/plugin-babel in the plugins array for them to work harmoniously together.

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

Transforming NodeJS Express HTTP responses into strings for AngularJS consumption

I have been working on creating an AngularJS program that communicates with an Express/Node.js API and a MySQL database. On the login page, I am successfully able to call the API which connects to MySQL. Depending on the correct combination of username an ...

In order to implement the functionality in JavaScript, the .slider::-webkit-slider

I need to create a slider that adjusts the size of the dot based on the value input. For example, when the value is 1, the dot size should be 10px and for a value of 100, it should be 100px. Is there a way to dynamically change the height of .slider::-web ...

Node.JS file upload fails to maintain the current state of uploaded files

I am encountering an issue with my Node.js server-side script where it successfully uploads a file to a specified directory, but it is not the intended file. The script throws an error message: Request received: POST undefined:1 ------WebKitFormBoundar ...

Trigger an email notification in Google Sheets whenever a designated cell is populated

I am currently exploring ways to enhance collaboration in project management, especially when dealing with numerous stakeholders (Although there are free tools available, integrating new procedures into a public organization's projects can be quite ch ...

React strict mode and Material UI console notifications

Just like a rapidly growing application can make the console as dirty as a footballer's shirt. What am I trying to convey? When using Material UI in strict mode, warnings such as FindDomNode may appear, or it may ask you to use strings instead of bo ...

Problem encountered with the @ManyToOne and @OneToMany declarations

Hello there! I recently embarked on a new project utilizing TypeScript, TypeORM, and Postgres. Everything seemed to be going smoothly until I encountered some perplexing errors related to a relationship between @ManyToOne and @OneToMany. Below are my entit ...

Encountered a problem with watchify while attempting to run the npm watch command

Hello there, I am currently following a tutorial on scotch.io where I am attempting to create a music player using electron and react. However, when I try to run 'npm run watch' I encounter the following error message: [email protected] watc ...

Exploring the capabilities of Redux Toolkit's createEntityAdapter in designing versatile data grids

Seeking guidance on utilizing createEntityAdapter from Redux Toolkit. In my application, I display package information and details using the master/detail feature of the AG Grid library. Packages are loaded initially, followed by fetching detailed data as ...

Error: Angular 4 component failed to load

It seems that the route /users is not functioning as expected; instead of loading the UsersComponent, it loads the AppComponent. Why is the /users route not loading the correct component? Here is a snippet from app.module.ts: import { Brows ...

Issue with object property not being recognized in Vue script, despite working fine in template

Currently, I am engaged in an exciting project using Vue. Within my Firestore database, I have a document named "default" within the collection "impostazioni" structured like this: impostazioni/default = { iniziata: false, finita: false, password: ...

Clicking on the image in the Swiper Slider will update the URL

Hi there! I am looking for help with changing the image URL when clicked. Currently, I am using swiper for my image gallery. I want to change this URL: to If anyone has a solution or suggestion on how I can achieve this, please let me know! ...

Encountering a syntax error while transferring information from Ajax to PHP

I am currently experiencing an issue with my Ajax and PHP setup. Upon checking the browser console, I encountered the following error message: The following error occured: parsererror SyntaxError: Unexpected token <. Despite multiple attempts at debugg ...

I am having trouble recognizing the final character within a string

Starting to learn Javascript and working on a basic calculator. My goal is to track the last character entered in the calculator display to prevent double symbols like (++, ./, *-, etc.) Since the input comes as a string, I've attempted using the met ...

Learning how to extract data from a JSON file using JavaScript

One of the challenges I'm facing involves a JSON file that looks like this: { "residents": [ { "name" : "Jacob", "title" : "King", "gender" : "Male", }, { "name" : "Luthor", ...

What is the reason behind the jQuery only functioning properly on Internet Explorer 8 on this particular page and no other browsers?

I recently created a webpage utilizing jQuery: The functionality on the page should change music images to represent different key signatures when switching from 'Higher Key' to 'Lower Key' in the combo box. While this works perfectly ...

Transferring the state from a parent component to a child function

I'm having trouble passing a state from a component to a function. I was able to pass the state from Home to ListHome, but I'm struggling to continue passing it to a function within ListHome (Slider) because it's a function. Even after revi ...

What is the best way to exhibit information from a lone table column in a modal using Angular 7?

Is there a way to have an "edit" button beside each row in the appointments table that triggers a modal popup allowing users to change appointment dates? Unfortunately, I'm facing an issue where the modal does not pop up and my screen turns white. ** ...

What steps should I take to ensure that the login page functions properly?

Below is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Pag ...

What is the best way to duplicate a node in the Angular UI tree?

Looking to efficiently clone nodes in an Angular UI tree along with all their children? I currently have an event click setup like this: ng-click="newSubItem(this)", where the function newSubItem is as follows: $scope.newSubItem = function (scope) { ...

How to extract a JavaScript object from an array using a specific field

When dealing with an array of objects, my goal is to choose the object that has the highest value in one of its fields. I understand how to select the value itself: Math.max.apply(Math, list.map(function (o) { return o.DisplayAQI; })) ... but I am unsur ...