简体   繁体   中英

Webpack Loaders JSX string to JSX

I put together a small loader so that when I require html files I will get JSX in return making use of this Htmltojsx converter

Unfortunately, since the loader just returns a string, my loader is crashing. I can verify from the loader that the string I am getting is what's expected:

import bodyHtml from './landing-body.html';

   const Landing = () => (
       <React.Fragment>
          <h3> Landing Page </h3>
          bodyHtml
          ...

And then the webpack build is crashing with this kind of error:

ERROR in ./Landing/landing-body.html
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <div>
|   <h5 className="product__title"> Your Product Name </h5>

Maybe I need to put in another loader for getting this from a string to raw JSX output?

Figured it out!

Since the first loader just returns a JSX string, there's still more transpiling to be done.

What I needed to use was webpack's 'loader chaining'

So in the end my html rule looks like this:

{   
            test: /\.html$/,
            exclude: /node_modules/,
            use: [
                {   
                    loader: 'babel-loader'
                },  
                {   
                    loader: path.resolve(__dirname, 'loaders/html-loader.js')
                }   
            ]
        }

I guess the chained loaders are done in 'reverse order' so to speak, so the html loader first converts it to a JSX string, and then the babel-loader treats that as JSX code.

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