Reputation: 1008
For code splitting purpose, I have my "posts" data in json format separated by file ie. sample-post-1.json
. I then have my <Post>
component targetted to import those posts dynamically (but the import must be sync for prerendering to work), smthing like:
// router
<Post path="/post/:slug" />
// Post
class Post extends Component {
constructor(props) {
super(props)
// try to dynamically lazy import, use import() to hint webpack we want to
// code split this module. but the "real" import needed to be sync
import(`@/data/posts/${this.props.matches.slug}`)
// require(...) doesnt work and throw error, no idea why. hence below
const post = __webpack_require__(
require.resolveWeak(`@/data/posts/${this.props.matches.slug}`)
)
this.state = { post }
}
render() {...}
}
Above works but it feels too hacky, are there alternative ways of achieving the same result without either __webpack_require__
/require.resolveWeak
?
Upvotes: 3
Views: 567
Reputation: 17989
The solution in your question is the only way I'm aware of currently.
However, the require
variable in your code is not present in all circumstances (eg. libraries with ES6 modules), so here is a version that works more generically (using only the __webpack_require__
variable):
declare var __webpack_require__;
function WP_ImportSync(name_ending: string) {
// Try to dynamically lazy import. Use import() to hint webpack we want to code split this module, but the "real" import needs to be synchronous.
import(name_ending);
//return __webpack_require__(require.resolve(name));
const moduleID = Object.keys(__webpack_require__.m).find(a=>a.endsWith(name_ending));
return __webpack_require__(moduleID);
}
Like you said, it ain't pretty, but it can get the job done. (so long as you know the parent project is using webpack, of course, as the standardized import(...)
function has no synchronous version that I'm aware of)
Upvotes: 2