Error message "require is not defined" encountered when importing a component in a Vue CLI build with target set to lib

I am currently in the process of exporting a Vue component as a package, utilizing vue cli to build the distribution. My goal is to publish it on npm, but for testing purposes, I am using a symbolic link. Despite starting with a basic hello-world project, I am unable to create a valid package.

To begin, I created a project:

vue create hello-world

Next, I made modifications to the package.json file:

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build --target lib --name vue-hello-world ./src/components/HelloWorld.vue",
    "lint": "vue-cli-service lint"
  },
  "main": "./dist/vue-hello-world.common.js",

After updating the script commands, I ran:

npm run build

The compilation process was successful without any errors.

However, when I attempted to import the packaged component into another Vue project (using a symbolic link in node_modules), I encountered the following error during page rendering:

[Vue warn]: Failed to resolve async component: function MediaViewerPdf() {
  return Promise.all(/*! import() */[__webpack_require__.e(62), __webpack_require__.e(46)]).then(__webpack_require__.bind(null, /*! ./viewers/MediaViewerPdf.vue */ "./vuejs/components/mediaViewer/viewers/MediaViewerPdf.vue"));
}
Reason: ReferenceError: require is not defined

Any insights on what might be causing this issue?

Additional Notes:

  • When running vue inspect, I confirmed that the webpack config has the line:

target: "web"

  • I have already set resolve.symlinks to false in the importing project.

EDIT: It has been verified that the issue persists even when utilizing the package directly from node_modules, ruling out potential issues related to the symbolic link.

For the full code repository, please visit: https://github.com/louis-sanna/vue-hello-world

Answer №1

After reaching out for help on the vue-cli repository, I was able to find the solution! https://github.com/vuejs/vue-cli/issues/4245

I discovered that my shell environment already had the NODE_ENV set to development, which was influencing the build mode.

All I needed to do was explicitly specify the mode like this:

vue-cli-service build --target lib --name vue-hello-world ./src/components/HelloWorld.vue --mode production

If necessary, you can also add it to your vue.config.js file:

config
  .mode("production")

Answer №2

This issue arises because the default Vue CLI Webpack setup does not import commonjs modules specified in the "main" field of package.json from the project that is trying to import them. The problem lies with the importing project, not with the one exporting the component.

There are two possible solutions to this problem:

  1. From the perspective of the importing project

To address this, you can install Babel plugins for the project importing your components and configure babel.config.js as follows:

module.exports = {
  presets: [
    '@vue/app'
  ],
  plugins: [
    '@babel/plugin-transform-modules-commonjs', // enables importing .common.js files
    '@babel/plugin-transform-modules-umd'       // allows importing .umd.js files
  ]
}

However, simply implementing these changes will not be enough; you also need to import the generated CSS from the library by adding the following line in your entry file:

import 'hello-world/dist/vue-hello-world.css';

Please note that I have only tested this using yarn link, but I believe it should work just fine with a separately imported npm module.

  1. From the perspective of the library

The main concern (presumably) behind the original question is how to bundle a library so users do not have to go through this process each time they want to use it.

Option 1: Do not bundle the library - provide .vue files and sources. Include everything in the 'src' directory of your module, write a readme with instructions, and leave the compilation and bundling tasks to the importing project.

Option 2: Utilize rollup with the Vue plugin to bundle components. There is an example demonstrating how to achieve this. By following that example, your project will be able to import the .esm build effortlessly. https://github.com/vuejs/rollup-plugin-vue/tree/master/cookbook/library

Answer №3

If you're unsure about how to go about creating a symbolic link, consider using the npm link command. In case you encounter any difficulties (just like I did), give npm-link-better a try:

npm install -g npm-link-better
cd vue-hello-world
npm link
cd ../hello-world
nlc -w vue-hello-world

When it comes to building component libraries, you might want to check out the vue-cli-plugin-component repository. This plugin is known for setting up vue-cli projects efficiently.

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

Error in Node.js Google Spreadsheets: The root element must be named 'Unknown name'

Currently, I am utilizing a discord bot to interact with a single Google Spreadsheet by reading and writing information. In order to achieve this, I have been delving into the intricacies of the Spreadsheet API, which unfortunately is poorly documented. De ...

Adapting the visual display according to the selected radio button output

Hey there, I've been working on a project of mine, but I'm struggling to fix a problem that has been puzzling me for quite some time. My webpage calculates the amount of calories needed to achieve specific training goals. I want to display three ...

There seems to be a mysql error with a syntax issue causing an ER_PARSE_ERROR with errno 106

Encountered a Syntax error: You have an error in your SQL syntax, please refer to the manual corresponding to your MySQL server version for the correct syntax to use near :data at line 1. errno: 1064 SqlState: '42000' This is The code used for ...

Looking for advice on utilizing Node.js and MongoDB to identify platform modifications on a website

I need guidance for a project I'm currently working on. The project involves extracting headers, like the example below in Mongo document format: { "url": "google.com", "statusCode": 301, "headers": { "location": "http://www.goog ...

Encountering an error: Reading an undefined property - NodeJS, Express, and Mongoose

These are the two functions I have: exports.list = function (req, res){ Material.find(function(err, materials) { res.render('materials/list', {title: 'Pagina Materiali', materials: materials}); }); } exports.modify = function (req ...

Tips for exchanging JSON data between HTML and PHP using jQuery Ajax?

Hello there! I am just starting to learn PHP and jQuery, and I have been experimenting with some code to understand how things work. However, I seem to be having issues with sending data back and forth between my webpage and the PHP file on the server. Her ...

What is the best way to showcase items in the shopping cart through a popup using Vue.js

Struggling to showcase cart items in a Vue js popup. Having difficulty only showing items that have been added to the cart. Check out the functional code pen here - https://codesandbox.io/s/competent-pine-8u9mt?file=/src/main.js ...

Effortless self-explanatory TypeScript / JavaScript code

How do you typically document your typescript or javascript code? When working with C# in Visual Studio, it's as easy as typing "///" to generate a documentation stub. But what are the recommended standards and tools for documenting typescript code? ...

Tips for optimizing AngularJS performance with large scopes

Currently, I am working on an Angular app for my company and have encountered a major issue. The app has become extremely slow, even after trying to optimize it using techniques like onetimebind and track by. Despite initial improvements, the performance i ...

Tips for successfully implementing JavaScript within innerHTML following an AJAX request

I am currently developing a voting system where users can click on buttons to cast their votes. When a button is clicked, an Ajax call is triggered to send data to another page which then performs SQL queries to insert the session ID, vote value, and vote ...

A guide on sorting MongoDB arrays in JavaScript to arrange them in descending order based on two specific fields

I am attempting to organize MongoDB arrays in a descending order. I have devised some JavaScript code to transform all the documents into JSON arrays, but I also need to arrange them in a descending order. Here is the code I have written: const result = xp ...

Using jQuery to extract all image sources from a parent element and remove a portion of the source URLs

I need to extract all the img src attributes from a parent element using a pointer in order to remove part of them. When I have an image selected, the src ends with _selected.jpg. Then, when I click on a link containing another image, I want to remove the ...

Modifying object colors on hover using three.js

As a beginner in the world of Three.js and WebGL, my first project involves creating a model of an animal and animating it in different ways, such as having its head follow the mouse cursor. The model consists of various geometries that are combined in sep ...

What is the reason Vue does not execute or update a computed property that contains a reference to 'this' within a filter function?

My question pertains to a select box that is linked to a Vue computed property. I am puzzled by the discrepancy in functionality between two of my computed property attempts. <select> <option v-for="option in filteredItems">{{option.descriptio ...

Avoid altering the background color through state variables in React

Currently, I am in the process of implementing a dark mode for my app. I have successfully created a state that changes the background color but encountered an issue with changing the background color of the textarea tag using a ternary operator when tryin ...

Confirm the authenticity of a JWT token using Express

My application has been encountering several errors, specifically: POST http://localhost:4000/api/payment/create-checkout-session 403 (Forbidden) AxiosError {message: 'Request failed with status code 403', name: 'AxiosError', code: &ap ...

Creating unique identifiers for each level within a multidimensional array using JavaScript

I'm currently working on creating a list that contains all the distinct levels within a multidimensional array of objects. Given this dataset... let levels = [ ["P", "B", "L"], ["A", "B", "L3"], ["A", "B", "L3"], ["P", "B", "M"], ["P", "C", ...

Navigating through Index in #each in emberjs

Take a look at the code provided below: http://jsbin.com/atuBaXE/2/ I am attempting to access the index using {{@index}}, but it doesn't seem to be compiling. I believe that handlebars should support this feature: {{#each item in model}} {{@index} ...

What is the best way to retrieve and store the contents of a .txt file that is accessible via HTTP into a JavaScript array,

I'm facing an issue where I have a .txt file accessible via http (for example, "", although not an actual link) and I am attempting to load it into a JavaScript array by lines using pure JavaScript. However, none of the solutions provided by others se ...

Incorporating an MVC View into a sophisticated JsonResult response

When I request Views from the MVC backend, I need more than just the content: public class CustomJsonViewResult { public string Subject { get; set; } public ActionResult View { get; set; } } As time goes on, this class will become more complex. ...