Import local Javascript module

First post here and pretty new to Javascript. I am trying to get familiar with script actions by reimplementing some of the existing actions in a local script in VS Code and then loading this script in the Drafts action.

Assume the following directory structure:

Scripts/
└── Custom Scripts/
    ├── editing.js
    └── utils.js

Is it possible to reuse functions across multiple files and if so, what is the correct way of importing these?

This works:

VS Code:

// editing.js

const insertText = (text, selectionStart) => {
  editor.setSelectedText(text);
  editor.setSelectedRange(selectionStart + text.length, 0);
};

const pasteClipboard = () => {
  const text = app.getClipboard();
  const [selectionStart, _] = editor.getSelectedRange();

  insertText(text, selectionStart);
};

Drafts action:

require("CustomScripts/editing.js")

pasteClipboard();

This does not work:

VS Code:

// utils.js

export const insertText = (text, selectionStart) => {
  editor.setSelectedText(text);
  editor.setSelectedRange(selectionStart + text.length, 0);
};
// editing.js

import { insertText } from "./utils.js";

const pasteClipboard = () => {
  const text = app.getClipboard();
  const [selectionStart, _] = editor.getSelectedRange();

  insertText(text, selectionStart);
};

Drafts action:

require("CustomScripts/editing.js")

pasteClipboard(); // Error: "Can't find variable: pasteClipboard"

I think you answered your own question with that given one works and one does not. :wink:

I don’t think import/export are supported by Drafts in that Drafts would need to support JavaScript Modules like modern browsers, Node.js, etc. do.

It certainly is possible to manage your code externally to Drafts. I put most of my code in to separate files and use VS Code (or Code on iPad) to manage the code in the same sort of way you set out.

This thread might be of interest on that front too if you are just getting started with your setup.

2 Likes