最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamic import() file in JS - Stack Overflow

programmeradmin4浏览0评论

I need to import markup file dynamically slice part of file and add result to variable and render result in my React app:

import('../changelog.md').then(...) 

I trying to do it in render() method with all logic but I have problems. Where I need to import it (in class or outside) and how to get value of promise to paste it to variable?

I need to import markup file dynamically slice part of file and add result to variable and render result in my React app:

import('../changelog.md').then(...) 

I trying to do it in render() method with all logic but I have problems. Where I need to import it (in class or outside) and how to get value of promise to paste it to variable?

Share Improve this question edited Sep 14, 2018 at 17:38 Prashant Pimpale 10.7k10 gold badges50 silver badges87 bronze badges asked Sep 14, 2018 at 15:56 user9576441user9576441 2
  • import() isn't any different than any other promise in this regard. Call setState in then. Wherever possible, use synchronous import. It's unclear from the question why would it be dynamic, since import module is known. – Estus Flask Commented Sep 14, 2018 at 17:11
  • assuming this is a real changelog, it isn't going to change while the app runs, because the app won't be silently live-updating itself. Parse the .md file to something JS can work with during your build step and bundle that in. – Mike 'Pomax' Kamermans Commented Sep 14, 2018 at 17:42
Add a ment  | 

3 Answers 3

Reset to default 5

Here's one way:

class MyComponent extends React.Component {

    state = {html: null}

    ponentDidMount() {
        import('../changelog.md').then(mod => {
            this.setState({html: mod.default})
        })
    }

    render() {
        return this.state.html ? <div dangerouslySetInnerHTML={{__html:this.state.html}} /> : <p>Loading...</p>
    }
}

Assuming you have a .md loader and it returns HTML.

import() returns a Promise. So you'll have to wait for it to resolve before you can render it. Easiest way to do that is to do it in ponentDidMount (React remends you put all ajax request there and this is kind of similar) and then copy it into state to force a re-render when it's done.

I'd use await keyword within an async method.

async function render() {
    var markup = await import('../changelog.md');
    // ...
}

import your .md file at start like this.

import yourMDObject from '../changelog.md';

and then you can use fetch() like this

fetch(yourMDObject).then(obj =>obj.text()).then(..)
发布评论

评论列表(0)

  1. 暂无评论