How to make script type both text/babel and module?

后端 未结 4 849
遥遥无期
遥遥无期 2021-02-07 06:59

It works perfectly because I haven\'t included JSX, but when I replace the script type with text/babel, it doesn\'t work because the module fails to load. bro

4条回答
  •  时光说笑
    2021-02-07 07:09

    I think the question was if it is possible to use a script tag with two or more types at the same time (e.g. something like type="module, txt/babel"). As far as I know the answer is NO.

    JonDotsoy's answer helps with reduce typing React.createElement over and over again but even with such a "variable shortcut" it's not as comfortable as JSX when using larger templates with nested elements because h('div', {}, 'hello!!')... is difficult to maintain in such cases.

    The only way I found to combine native browser module support and in-browser Babel for JSX without using any build tool is this ... a rather dirty hack that uses eval and should not be used for production apps:

    index.html

    
    
        

    app/app.js

    import ComponentOne from "./ComponentOne.js";
    
    
    let template = `
    

    Heading


    `; const App = () => { return ( eval(Babel.transform(template, { presets: ['es2017', 'react'] }).code) ); }; ReactDOM.render( React.createElement(App, null), document.getElementById("app") );

    app/ComponentOne.js

    import ComponentTwo from "./ComponentTwo.js";
    
    
    let template = `
    

    This is ComponentOne

    Property "msg" content: {props.msg}

    `; const ComponentOne = (props) => { return( eval(Babel.transform(template, { presets: ['es2017', 'react'] }).code) ); }; export default ComponentOne;

    app/ComponentTwo.js

    let template = `
    

    This is ComponentTwo

    Property "msg" content: {props.msg}

    `; const ComponentTwo = (props) => { return( eval(Babel.transform(template, { presets: ['es2017', 'react'] }).code) ); }; export default ComponentTwo;

提交回复
热议问题