I am building a gatsby site where each page is generated from a template, but each page requires a different module import.
Specifically, each page contains an observablehq notebook, and these are exported from observable as modules. See here.
The pages are dynamically generated from a json
file like:
[
{ "path": "page1",
"modulename": "gatsby-test"
},
{
"path": "page2",
"modulename": "gatsby-test-2"
}
]
This is done using createPages
in gatsby-node.js
.
I have already yarn add
ed each notebook the project, e.g. yarn add https://api.observablehq.com/@robinl/gatsby-test.tgz
.
I'm trying to write a component which takes the module name as a property, and then loads the right module from the contents of this.props
.
An outline of my component looks like:
class ImportedNotebook extends Component {
componentDidMount() {
var promise = import(this.props.modulename).then(function(themodule) {
// do stuff here
})
}
render() {
return (<div>blah</div>);
}
}
This does not work - I get an Unhandled Rejection (Error): Cannot find module 'gatsby-test-2'
error when visiting the page on localhost using gatsby develop.
However, if I replace this.props.modulename
with "gatsby-test-2"
it works fine.
Is there a way of dynamically loading modules from a variable? Or perhaps a different approach that would be more suitable to solve this problem?