Null reference from MySQL driver module from taskpane.js a Microsoft Office Add-In

Viewed 103

I'm trying to access a MySQL database from a Microsoft Office Add-In. I can get the Add-In to work in MsWord, but when I try to use the MySQL Node.js driver, the "mysql" object shows up as null at runtime.

I added this at the beginning of taskpane.js:

import { mysql } from 'mysql';

did the following:
npm install mysql
npm audit fix
npm install @types/mysql
added the following to webpack.config.js "target: 'node',"

and later in the code, when I run it this fires and shows "mysql undefined":

 if (!mysql) {
  context.document.body.insertParagraph("mysql undefined", Word.InsertLocation.end);

What am I missing or doing wrong?

2 Answers

This wouldn't work, since you're trying to use a server library mysql in your front-end. While both are written in javascript, the environments they are working on are very different.

Diagram below explains it pretty neatly - sourced from this website which I'm recommending you to check out.

enter image description here

In essence, for react library, you are using node.js as a *.jsx or *.js build helper, packaging runner, etc.. so end result should be just a javascript file. Something like main.123456.js if you're using create react app's default build. That file will be meaningful in browser context, since you'll have DOM items here, HTML specific stuff.

For MySQL library - you are using node.js as a HTTP server. That won't have access to the DOM, but because it's running as a process on some compute unit, it'll provide you different capabilities, which enable your MySQL connection to work.

office.js operates in browser context, you're basically writing your app with react and just referencing some office.js APIs. That means the line below belongs to your react app:

context.document.body.insertParagraph("mysql undefined", Word.InsertLocation.end);

Your data from MySQL needs to come from your server though. You can use node.js as a server, that way you'll be able to use the MySQL library that you've imported from NPM. This tutorial walks you through how to setup a very simple server.

That means this line

import { mysql } from 'mysql';

and the sql connection belongs to the server side running on node.

You need ti declare the variable first

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "username",
  password: "password",
  database: 'satavasename',
  port: 3306,
  ssl: true
});
Related