ERROR: mammoth has not been declared

I've been attempting to integrate the mammoth npm library with my Meteor project.

When using the import command, import { mammoth } from "mammoth";, I encountered

Uncaught TypeError: Cannot read property 'bind' of undefined

After trying the command, declare var mammoth: any;, I faced

EXCEPTION: mammoth is not defined

The code snippet I'm using is as follows:

this.readFileInputEventAsArrayBuffer(event, function(arrayBuffer) {
      mammoth
        .convertToHtml({ arrayBuffer: arrayBuffer })
        .then(function(result: any) {
          var html = result.value; // The generated HTML
          var messages = result.messages; // Any messages, such as warnings during conversion
          // console.log('html: ' + html);
          document.getElementById("output").innerHTML = html;
          var elements = document.getElementById("output").children;
          console.log(elements);
          console.log(JSON.stringify(elements));
          console.log(elements.length);
          for (var i = 0; i < elements.length; i++) {
            console.log(i + " --- ");
            console.log(elements[i]);
            var data = elements[i].innerHTML;
            // elements[i].setAttribute("draggable","true");
          }
        })
        .done();
      console.log(
        "event in fileUpload-readFileInputEventAsArrayBuffer" + event
      );
    });

 readFileInputEventAsArrayBuffer(event, callback) {
    var file = event.target.files[0];

    var reader = new FileReader();

    reader.onload = function(loadEvent: any) {
      var arrayBuffer = loadEvent.target.result;
      console.log("arrayBuffer: ");
      console.log(arrayBuffer);
      callback(arrayBuffer);
    };

    reader.readAsArrayBuffer(file);
  }

Upon using the import

declare var mammoth: any;

I encountered the error:

ReferenceError: mammoth is not defined
at app.component.ts:75
at FileReader.reader.onload (app.component.ts:109)
at ZoneDelegate.invoke (modules.js:22723)
at Object.onInvoke (modules.js:57096)
at ZoneDelegate.invoke (modules.js:22722)
at Zone.runGuarded (modules.js:22607)
at FileReader.<anonymous> (modules.js:22585)

Uncaught ReferenceError: mammoth is not defined
at app.component.ts:75
at FileReader.reader.onload (app.component.ts:109)
at ZoneDelegate.invoke (modules.js:22723)
at Object.onInvoke (modules.js:57096)
at ZoneDelegate.invoke (modules.js:22722)
at Zone.runGuarded (modules.js:22607)
at FileReader.<anonymous> (modules.js:22585)

Upon using the import

import { mammoth } from "mammoth";

I encountered the error:

Uncaught TypeError: Cannot read property 'bind' of undefined
at meteorInstall.node_modules.mammoth.lib.docx.files.js (modules.js?hash=cd1f432…:83272)
at fileEvaluate (modules-runtime.js?hash=637cb12…:191)
at require (modules-runtime.js?hash=637cb12…:116)
at meteorInstall.node_modules.mammoth.lib.docx.docx-reader.js (modules.js?hash=cd1f432…:82091)
at fileEvaluate (modules-runtime.js?hash=637cb12…:191)
at require (modules-runtime.js?hash=637cb12…:116)
at meteorInstall.node_modules.mammoth.lib.index.js (modules.js?hash=cd1f432…:81954)
at fileEvaluate (modules-runtime.js?hash=637cb12…:191)
at require (modules-runtime.js?hash=637cb12…:116)
at meteorInstall.client.imports.app.app.component.js (app.component.ts:12)
at fileEvaluate (modules-runtime.js?hash=637cb12…:191)
at require (modules-runtime.js?hash=637cb12…:116)
at meteorInstall.client.imports.app.index.js (index.ts:1)
at fileEvaluate (modules-runtime.js?hash=637cb12…:191)
at require (modules-runtime.js?hash=637cb12…:116)
at meteorInstall.client.main.js (main.ts:5)
at fileEvaluate (modules-runtime.js?hash=637cb12…:191)
at require (modules-runtime.js?hash=637cb12…:116)
at demo.collection.ts:4

Can anyone provide assistance with this issue?

P.S.: The mammoth library works correctly in an Angular project. The problem arises when attempting to use it in an Angular-Meteor project.

Answer №1

Give it a shot and see if this solution does the trick:

import 'mammoth/mammoth.browser';
(browser version)

If you prefer to handle this on the front-end, you can include the following scripts in your HTML page and process it during runtime. (Converting document to HTML and displaying)

  • You can also refer to this article for more information ->

Scripts to be added:

  • demo.js ->
  • mammoth.browser.min.js ->

Hopefully, this information proves helpful.

Answer №2

Upon inspecting the source code of the mammoth npm package, it becomes evident that there is no direct export of 'mammoth' or default function. Instead, each method is exported individually, allowing for a specific approach when using the package:

import {convertToHtml} from "mammoth";

convertToHtml({path: "path/to/document.docx"})
    .then(function(result){
        var html = result.value; // The HTML content generated 
        var messages = result.messages; // Any alerts or warnings produced during conversion 
    })
    .done();

Following this pattern should solve the issue at hand :)

Answer №3

To successfully import, you can do it in the following way:

import {htmlConverter} from 'mammoth/mammoth.browser';

Within your component.ts file:

import {htmlConverter} from "mammoth/mammoth.browser";
                   

htmlConverter({ arrayBuffer: arrayBuffer })
.then(function(output){
    var htmlOutput = output.value; // The HTML that was generated
    var alerts = output.messages; // Any alerts or notifications during the conversion
})
.done();

The code above has proven to be effective in my implementation with Angular 9.

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: Unable to import a module installed globally

I've been attempting to include the NPM package browserify, which I have installed globally using this command: npm install -g browserify In the file bundle.js, I'm trying to require browserify like so: var browserify = require('browserif ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

When `focus` is bound to a jQuery event handler, the behavior of the select element becomes erratic on

What causes the odd behavior where users need to click twice on a select-option for it to drop down/up after binding an eventhandler to the focus event using jQuery? $('input, select, textarea').focus(function() { $(this).addClass('input_ ...

Encountering difficulties in sending the data to Firebase through the contact form

import React, { useState } from 'react' import styled from 'styled-components' import Title from '../Components/Title' import { InnerLayout, MainLayout } from '../Styles/Layout' import ...

Ways to specify the styles for tr, td, and label elements within a material table

Hey there! Currently, I'm working with material table in react. I came across this page: https://material-table.com/#/docs/features/styling, where it mentions that we can use cellStyle, headerStyle. But what if I want to add more detailed styles to e ...

Exploring the functionality of Async Storage in React Native for efficient data saving purposes

I'm completely new to working with Async and async storage. I am a bit lost and unsure of how to proceed, but my main objective is to use setWorkouts() to assign workouts based on the values I retrieve from asyncstorage, and then save these workouts. ...

Error: The $filter function in AngularJS is not recognized

I have been attempting to inject a filter into my controller and utilize it in the following manner: angular .module('graduateCalculator', []) .filter('slug', function() { return function(input) { ...

Guide to returning data in response to a GET request in ASP.NET MVC using ActionResult

I am currently facing a challenge with creating a method to handle an AJAX GET request from JavaScript. Upon debugging, I have confirmed that the GET response method in the backend is retrieving the correct data. However, I am uncertain about how to effect ...

The ajv-based middy validator does not adhere to the specified date and time format

When it comes to validation, I rely on middy as my go-to package, which is powered by ajv. Below is an example of how I set up the JSON schema: serviceDate: { type: 'string', format: 'date-time' }, The structure o ...

Vue 3 gracefully handles errors by displaying an alternative component

I am currently developing a rendering library for my Vue 3 + Vite project. Essentially, I have a JSON array of products which I pass to a special <Render :products /> component. This Render component reads all the JSON products and converts them in ...

"Is there a function for the event emitter in Node.js using ES6

I'm currently in the process of developing a class in which every instance can react to an event: const events = require("events"); const eventEmitter = new events.EventEmitter(); class Camera { constructor(ip) { this.ip = ip; } ...

Change the image source URL dynamically using npm webpack

I am attempting to create a reusable module that will be utilized by other modules, but I have encountered an issue with including HTML files within the module. The first module is located at c:/module_1 and contains the following base HTML: <img src=" ...

Mobile-responsive iFrame content is designed to adjust and fit appropriately on

While my iframe is responsive on both mobile and website, I am facing an issue where the content overflows (both overflow X and Y) from the width and height of the iFrame. Here's the scenario: in the mobile view (simulated using Google Chrome to mimi ...

Prevent Float Filtering in AngularJS

As I work on creating a directive in AngularJs, I am facing an issue. The directive is supposed to receive a JSON object from the app controller and display its content accordingly. To better illustrate my problem, I have created a simple demo which can b ...

Guide: "Sending an AJAX request upon selecting an item in a Vue.js 'Select' element using vue-resource"

Is it possible to send an ajax request through vue-resource when a specific item is selected from a "Select" in vuejs? Check out the demo here: https://jsfiddle.net/xoyhdaxy/ <div class="container" id="app"> <select v-model="selected"> ...

Possibility for using navigator.GetUserMedia in Internet Explorer

How can I access a webcam through JavaScript/jQuery? I have successfully opened the webcam in Chrome and Mozilla, but the navigator.GetUserMedia feature does not work in Internet Explorer. Is there a way to achieve this with JavaScript or jQuery in IE? ...

Comparing Two Arrays in AngularJS and Disabling on Identical Cases

I currently have two tables: "Available subject" and "Added subject" which are populated by ng-repeat with two separate lists of objects. My objective is to accomplish three things: 1 - When the user clicks on the plus sign, a row with identical content s ...

Transforming a JavaScript component based on classes into a TypeScript component by employing dynamic prop destructuring

My current setup involves a class based component that looks like this class ArInput extends React.Component { render() { const { shadowless, success, error } = this.props; const inputStyles = [ styles.input, !shadowless && s ...

Unexpected issues have arisen with the $.ajax function, causing it

I am facing an issue where I can see the loader.gif but unable to view avaiable.png or not_avaiable.png in my PHP file. What could be causing this problem? $(document).ready(function()//When the dom is ready { $("#inputEmail").change(function() { ...

Why isn't my file being recognized post-multer middleware?

I am currently facing an issue with uploading a filename and a post (similar to 9GAG style) to my MySQL database, and storing the file in my project folder. The front end is able to retrieve the file without any problems (verified through console.log), but ...