Discovering an npm module within an ember-cli addon component

I recently encountered an issue while using ember-browserify to locate npm modules in my ember-cli applications - it seems to not function properly for ember-cli addons.

This leads me to wonder: Are there alternative methods for importing npm modules into an ember-cli addon?

Update:

Although I faced difficulties importing the npm module, I discovered that the specific module I needed was also available as a bower component. Therefore, I successfully installed it and imported it through the index.js file as shown below:

included: function(app) {
  this._super.included(app);

  app.import('bower_components/dropzone/dist/dropzone.js');
}

Using this approach resolved the issue. Unfortunately, importing npm modules directly from node_modules proved to be challenging. It's frustrating that incorporating npm modules into an ember-cli addon is so complicated.

Answer №1

If you're looking to implement this functionality, ember-fetch has a solution available. The code may seem a bit complicated at first glance:

treeForVendor: function(tree) {

  // Determining the path for whatwg-fetch in node modules
  var fetchPath = require.resolve('whatwg-fetch');

  // Applying a utility function to expand it into a pattern
  var expandedFetchPath = expand(fetchPath);

  // Renaming all files in a tree with items matching the pattern
  var fetch = rename(find(expandedFetchPath), function(path) {
    return 'whatwg-fetch/fetch.js'
  });

  // Implementing a template for each file in the tree and then merging them
  return mergeTrees([
    new Template(fetch, templatePath, function variables(content) {
      return {
        moduleBody: content
      };
    })
  ]);
},

included: function(app) {
  this.app = app;
  this._super.included(app);

  // Importing the created tree from the treeForVendor function
  app.import('vendor/whatwg-fetch/fetch.js', {
    exports: {
      default: [
        'default',
        'Headers',
        'Request',
        'Response'
      ]
    }
  });
}

Extracted from https://github.com/stefanpenner/ember-fetch/blob/master/index.js

Hopefully, this explanation aids your understanding.

Answer №2

To implement the addon, remember to include the import statement for the app/ version of the object (which typically only exports the object).

In the applications that utilize the addon, make sure to install both ember-browserify and the required npm module.

For instance, in the app/models/user.js file within an addon:

import TimezoneDetect from 'npm:jstimezonedetect';

export { default } from 'common/models/user';

Refer to https://github.com/ef4/ember-browserify#using-ember-browserify-in-addons

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

Upgrade to a more stable configuration version for Nodemailer as the current configuration is not supported. Consider down

I'm currently utilizing Nodemailer version 2.6.4 with Node version 6.9.1 var nodemailer = require("nodemailer"); var wellknown = require('nodemailer-wellknown'); var transporter = nodemailer.createTransport("SMTP",{ service: "yahoo", ...

Automatically browserify files whenever there is a change using tsc -w

As someone who is new to npm build tools, I am looking to automatically bundle compiled typescript files whenever a change occurs in the typescript files. Additionally, I want to run lite-server concurrently. In order to achieve this, I have created the fo ...

Switch out the content within a div upon selection

I'm currently working on a palette board project and facing some challenges when switching to a different theme. The initial page is set to have a Warm color palette, but I intend to alter this once the user clicks on the All theme option. Users wil ...

Swap out a div identifier and reload the page without a full page refresh

I am interested in learning how to dynamically remove a div id upon button click and then add it back with another button click to load the associated CSS. The goal is for the page to refresh asynchronously to reflect these changes. So far, I have successf ...

Extracting information from JSON using jQuery

this is a sample json object: { "box 1": [{ "difficulty_grade": "5a+" }, { "gym": "New_gym" }, { "route_author": "some author" },]} Here is the code snippet: variable groups contains JSON data as shown in the image. for (var k in groups){ $p ...

Running a cfquery in a cfc and passing parameters through AJAX

I am currently setting up a system to retrieve data from my ColdFusion database using JavaScript. However, I am encountering an error and unsure of its cause since I am relatively new to CF. The specific engine I am utilizing is ColdFusion MX 7. Below is ...

Adding a JavaScript widget to a WordPress page

Good morning! I need to place an affiliate external widget on a WordPress page. The code I have loads external content within the page. <script type="text/javascript" src="http://www.convert.co.uk/widget/mobiles.js"></script> The placement o ...

Showcasing Portfolio Work in a User-Friendly Mobile Design

Currently revamping my portfolio website and looking for ways to optimize the display of my personal projects. I have a card-like interface in place that works well on desktop but only shows one project at a time on mobile devices. Seeking solutions to imp ...

Locating the save directory with fileSystem API

I've been working on saving a file using the fileSystem API. It appears that the code below is functional. However, I am unable to locate where the saved file is stored. If it's on MacOS, shouldn't it be in this directory? /Users/USERNAM ...

The execution of the npm command was unsuccessful due to the dashlane/cli issue

I'm currently attempting to set up the dashlane-cli using PowerShell. However, I've run into an issue during the installation process. PowerShell is displaying an error message stating that it could not execute the command. It seems that the prob ...

What is the best way to transform a standard select input into a React select with multiple options?

Is it possible to transform a regular select dropdown into a multiple select dropdown in React, similar to the one shown in this image? I'm currently using the map method for my select options. https://i.stack.imgur.com/vJbJG.jpg Below is the code s ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

I downloaded NPM using PIP, however I am receiving the error message "npm: command not found"

Having Python 2.7 installed on OS X Yosemite 10.10.5, I attempted to install NPM via PIP. The installation seemed successful as there is a directory named npm in /Library/Python/2.7/site-packages/. However, whenever I try to use NPM, it returns "command no ...

How to Fetch Byte Image with Ajax and Display it on the Client Side in ASP.Net MVC

After converting an image to bytes, I am facing the challenge of displaying the byteImage in a browser. I have two sets of data, one being the Image ID and the other being the Image_name, which are displayed in a table. However, I am unable to display the ...

Encountered issue while converting half of the string array to JSON using JavaScript

I encountered an issue with the code below while trying to convert an array into JSON. Here is my code: <html> <head> </head> <body style="text-align:center;" id="body"> <p id="GFG_UP1" style="font-size: 16px;"> </p ...

What is the best way to retrieve the name of a Meteor package from within the

As I work on developing a package, I am looking for ways to dynamically utilize the package's name within the code. This is particularly important for logging purposes in my /log.js file. My main query is regarding how I can access the variable that ...

Resolving redundancy in Typescript Material-UI Table codebases

Apologies for the ambiguous question title, it was difficult to come up with something more specific. I am currently exploring the Typescript implementation of Material-UI tables, specifically focusing on the table section titled "Sorting and selecting". ...

Do we need to use the render method in ReactJs?

I'm curious about how ReactJs uses its Render() functionality. Let's say we have some HTML code within index.html: <section id="Hello"> <h1>Hello world</h1> <p>Something something Darkside</p> </section&g ...

I keep encountering the "Error: EACCES, mkdir" message every time I attempt to install a new package using bower

I've been attempting to set up bootstrap using bower. I have successfully installed bower globally with npm. However, each time I try to install bootstrap with bower, I encounter the following error message - Stack trace: Error: EACCES, mkdir &apo ...

The absence of the 'Access-Control-Allow-Origin' CORS header was noticed in the response from the Wikipedia API

Attempting to retrieve data from the Wikipedia API using axios in reactJS. Here is my request: axios.get('https://en.wikipedia.org/w/api.php?action=opensearch&search=lol&format=json&callback=?') .then((response) => { c ...