cannot use import statement outside a module - Excel custom functions add-in: proper way to use JS functions defined in taskpane.js in functions.js

Viewed 53

Newbie here in Office add-ins and JavaScript, so please be patient!

I created a Javascript Excel custom functions add-in, by using the Yeoman generator. In one of my custom function I want to use a JS function defined in an external file. So I defined a function named testExternal and placed it in taskpane.js file:

export function testExternal() {
  return 1;
}

then in the functions.js file I have:

import { testExternal } from "../taskpane/taskpane.js";

and in my custom function:

console.log(testExternal());

When debugging, I'm getting the desired 1 in console, but also get the "Cannot use import statement outside a module" error message:

enter image description here

This happens not only in debug mode, but also when the add-in is published on a web server and the add-in is sideloaded. So the external defined function is working correctly, but:

  1. is there any way to get rid of that error message?
  2. what are the steps to use a function defined in another JS file (not in taskpane.js)? Let's say I want to have all my utils functions in a file named utils.js and use that in my custom functions. What is the best location for utils.js and how can be automatically added to the dist folder, when the project is build in VS Code?

Thank you for your time,

Adrian

1 Answers

javascript + html :

If you are using native javascript "for browser" (I'm mean it's not a node application that use packages, etc...). When you import a script where you need to use import statement you need to set his type as module :

<script src="app.js" type="module"></script>

utils.js
function foo() {
    return 'Hello';
}

export { foo };

This one is a module :

app.js
import { foo } from 'utils.js';

node.js :

If you want want to use ES Modules you have to set the property type of your package.json as module :

package.json
{
    "type": "module"
}

If office add-in doesn't allow you to use ES Modules you have to use Nodes modules to import / export things :

utils.js
function foo() {
    return "Hello";
}

module.exports = foo;
// or
module.exports.foo = foo

Then :

const foo = require('utils');
// or
const { foo } = require('utils');
Related