Moving an inline function to a component in Framework

I’m new to Observable in general (never used the hosted version) but super excited about the new self-hosted Framework.

I am following the documentation and reading in the Javascript Imports section about moving code to components.

I had an inline JS block that had a function like:

const myFunction = (data, {width} = {}) {
  return Plot.plot(/* function stuff */)
}

And further down in my Markdown file I had:

<div class="card">${resize((width) => myFunction(data, {width})}</div>

This worked just fine inline and displayed my chart with the data as expected.

Then I created a file called myFunction.js and put it in the docs/components folder as was suggested in the Routing docs. The file looks like this:

export const myFunction = (data, {width} = {}) {
  return Plot.plot(/* function stuff */)
}

Then in my Markdown file, I have this in a JS block instead of the inline declaration of myFunction.

import { myFunction } from './components/myFunction.js';

So far so good… The dev preview isn’t throwing any errors in the console or on the page.

However, my chart doesn’t show up now, and I can’t quite figure out what I’m doing wrong?

One thing I thought of was maybe I needed to import Plot in my component file since it’s not in the Markdown anymore, but that throws an error when I do it, complaining that it’s not a local import so that’s not it?

Suggestions/help welcome!

You don’t get implicit imports in JavaScript, only in Markdown. And you have a syntax error where you’re missing the => in your arrow function declaration. So at a minimum you’ll need to say:

import * as Plot from "npm:@observablehq/plot";

export const myFunction = (data, {width} = {}) => {
  return Plot.plot(/* function stuff */);
};

Though I recommend using a function instead of a const declaration for style…

import * as Plot from "npm:@observablehq/plot";

export function myFunction(data, {width} = {}) {
  return Plot.plot(/* function stuff */);
}

Thanks you for the assistance, I figured it out… :duck:

It was sadly a dumb error on my part. In the Plot.barX() call within the function itself I was directly referencing the original array instead of the variable passed in via the function call (i.e. the data var). I missed it while refactoring.

So it still worked inline because that original array was in the page scope, but when I moved it out to a component, it was an empty variable, and so no chart to draw.

Although I guess I’m surprised it didn’t complain about an undeclared value within the function?

Anyways, thanks you again… For the help, and for this amazing framework!