简体   繁体   中英

Webpack: How to parse html templates residing in js file?

I am developing a simple embeddable widget that has no .html files, only .js and .css. All the necessary HTML markup is produced within .js files. Ie

function closeWidget() {
  // closeWidget
}

function widgetRenderer() {
  return `
    <div class='widget-header'>
      <span class='widget-close' onclick='closeWidget();'><b>_</b>
    </div>
  `
}

The problem I am facing is: once the code snippet is attached to the website, the onclick action will not work, because of webpack minifying closeWidget function name. How can I tell webpack to run through these 'inline html snippets' and modify them as well? Is it even possible?

You can't do it that way, onclick is a dom event, it's not "run" by webpack, but the dom it's self. So the html is rendered to the browser, and when you click the span, the event is fired and the browser looks for an exposed js function called closeWidget , which dosnt exist, because it's within the component scope, and not accessible normally.

What are you not using react normally with jsx? It would be as simple as:

function closeWidget() {
  // closeWidget
}

render() {
  return (
    <div className='widget-header'>
       <span className='widget-close' onClick={this.closeWidget}><b>_</b>
    </div>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM