I am trying to import a module for context-free grammars, but am really struggling to get this working on an Observable page.
The module is grammar-graph - npm
If I try the module require debugger, it suggests either
import('https://cdn.skypack.dev/grammar-graph@3.1.1?min')
or
require('grammar-graph@3.1.1/lib/grammar-graph.js').catch(() => window["parseGrammar"])
but neither of these seem to give me access to content, for example, the new GrammarGraph
constructor.
I realise importing modules can be difficult, but I really struggle to know what the cause of the problem is here, or where to look to find the cause and remedy it.
Does anyone have any advice?
With ES Modules you may have to pull out the default export. That seems to be the case here, so this works:
GrammarGraph = (await import("https://cdn.jsdelivr.net/npm/grammar-graph@3.1.1/+esm")).default
graph = new GrammarGraph({
Sentence: ["NounPhrase VerbPhrase"],
NounPhrase: ["the Noun", "the Noun RelativeClause"],
VerbPhrase: ["Verb", "Verb NounPhrase"],
RelativeClause: ["that VerbPhrase"],
Noun: ["dog", "cat", "bird", "squirrel"],
Verb: ["befriended", "loved", "ate", "attacked"]
})
Live demo: Hello, GrammarGraph / Observable / Observable
I’m using esm.run instead of Skypack but either will work.
That’s great - thanks very much.
Is there anywhere documentation that would lead me (or anyone else) to such a solution? The How to: require stubborn modules is very useful in many respects, but I don’t think I would have ever discovered this as a solution, nor known what it was to look for to give a clue that this would have been the right approach.
This is the standard behavior of dynamic import in JavaScript, so you could look at MDN:
1 Like