It seems I have a fundamental lack of understanding when it comes to import
vs require
. From what I've read I know the difference is that require
is based on a module loaders like CommonJS
while import is actually an ES6 feature.
Assuming the following:
import ExamplePost from 'example-post.md'
This is an example import with MDX JS as appropriate loader and I set this in my React render function like:
render () {
return <ExamplePost />
}
The above works perfectly fine, but as I want to dynamically load different Markdown files and I have read that ES6 import
are static I intended to go like:
let postName = 'example-post'
const ExamplePost = require(`${postName}.md`)
Unfortunately it doesn't work, I am getting: ExamplePost is not defined
I'm setting both examples at the top of the document. I also inspected both versions and I can see a difference in the outcome:
ES6 import returns: [Function]
Require returns: Object [Module] { default: [Function] }
Help to get me on the right track on why the require above does not work the same?
You import
the default export of module and require
the module itself.
const ExamplePost = require(`${postName}.md`).default
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Also check Can't require() default export value in Babel 6.x
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments