Mailchimp and Node.js with typescript noob question: Import vs Require

Viewed 3424

I am creating an app that sends certain transactional emails using Mailchimp.

They have great docs here: https://mailchimp.com/developer/api/transactional/messages/send-using-message-template/

But Im using typescript, so the line:

var mailchimp = require("mailchimp_transactional")("API_KEY");

Doesn't work, I get the following error:

Error: Cannot find module 'mailchimp_transactional'

I know this is something small, but I am not sure how to get around it at all. I found an article that describes creating your own types file here: @mailchimp/mailchimp_marketing/types.d.ts' is not a module in nodeJs

But there has to be a quicker simpler solution. It also doesn't make it clear how to set the API key in that case.

I have tried to import the module which is @mailchimp/mailchimp_transactional which did not work. I have ofcourse also run npm install @mailchimp/mailchimp_transactional

Any help would be appreciated, here is a full sample just incase it helps.

var mailchimp = require("mailchimp_transactional")("API_KEY");

export const testSendEmailFromTemplate = async () => {
    let mcbody = {
        template_name: "my-template",
        template_content: [{
            name:"firstname",
            content:"INJECTED.BY.TEMPLATE.CONT.firstname"
        },
        {
            name:"surname",
            content:"INJECTED.BY.TEMPLATE.CONT.surname"
        }],
        message: {
            to:{
                email:"email@gmail.com",
                name: "Test",
                type: "to"
            }
        },
        async:true
    };
    return await mailchimp.messages.sendTemplate(mcbody);
}

2 Answers

If anyone is unfortunate enough to face this issue because Mailchip's docs don't cater to the typescript setup, and you aren't sure how to make it 'just work' here is the answer:

const mailchimpFactory = require("@mailchimp/mailchimp_transactional/src/index.js");
const mailchimp = mailchimpFactory("PUTKEYHERE");

This pulls in the javascript file directly and then the second line initialises the object.

Good luck all!

I had the same problem in a node/Typescript project, but this is working for me:


const mailchimp = require('@mailchimp/mailchimp_marketing')

export class MailchimpServices {

constructor() {

    mailchimp.setConfig({
        apiKey: '...',
        server: 'us5',
    });
}


async ping() {
    console.log('Start mailchimp ping!')
    const response = await mailchimp.ping.get();
    console.log(response);
}

}

Related