简体   繁体   English

我可以用反应框架的哈巴狗(ex-jade)吗?

[英]can i use pug (ex-jade) with react framework?

i have read some of pug documentation. 我读过一些哈巴狗文档。 its said that i have to install pug first and i'm already done that. 它说我必须先安装哈巴狗,我已经完成了。 then i have to require pug in my js file. 然后我必须在我的js文件中要求哈巴狗。 but i don't know where to write the compile for pug file in my react files? 但我不知道在我的反应文件中编写pug文件的编译在哪里? what is the right steps to use pug in react framework? 在反应框架中使用哈巴狗的正确步骤是什么? thanks! 谢谢! i really appreciated any help. 我真的很感激任何帮助。 here is one of my component in react that i would like to render it with pug. 这是我的反应中的一个组件,我想用哈巴狗来渲染它。

 import React from 'react';
 import Sidebar from './Sidebar';
 import Header from './header/Header';
 import {tokenverify} from '../../utils/helpers';
 import pug from 'pug';

 class Home extends React.Component {
   componentDidMount() {
     const token = localStorage.getItem('token')
     tokenverify(token)
     .catch((res) => {
       this.props.history.push('/')
     })
   }

   render() {
     return(
       <div className="main-container">
         <div className="col-md-1">
           <Sidebar history={this.props.history} username={this.props.params.username}/>
         </div>
         <div className="col-md-11">
           <div className="row">
             <Header history={this.props.history} username={this.props.params.username} />
           </div>
           <div className="row">
             {this.props.children}
           </div>
         </div>
       </div>
     )
   }
 }

 export default Home

I found this project in very early phase of its development : https://github.com/bluewings/pug-as-jsx-loader . 我发现这个项目处于开发的早期阶段: https//github.com/bluewings/pug-as-jsx-loader

I like it because it lets me write my dumb (presentational) react components as pug templates. 我喜欢它,因为它让我把我的哑(表象)反应组件写成pug模板。

The only JSX functionality it currently supports are iterating and conditional if. 它目前支持的唯一JSX功能是迭代和条件if。 Which seems good enough for writing most of the dumb components. 这似乎足以写出大部分愚蠢的组件。

Here are the steps to use it 以下是使用它的步骤

1. Install pug-as-jsx-loader 1.安装pug-as-jsx-loader

npm install pug-as-jsx-loader --save-dev

For next step you will have to eject if you are using create-react-app 对于下一步,如果使用create-react-app,则必须弹出

2. Tell webpack how to handle pug templates. 2.告诉webpack如何处理pug模板。

In your webpack.config.dev.js, 在你的webpack.config.dev.js中,

{ test: /\.pug$/, use: [require.resolve('babel-loader'), require.resolve('pug-as-jsx-loader')] },

3. Import pug template in your component 3.在组件中导入pug模板

import myTemplate from './mycomponent.pug'

4. Return compiled template from render function 4.从渲染函数返回编译的模板

const MyComponent = ({someProperty, someOtherProperty})=> {
  return myTemplate.call({}, {
    someProperty,
    someOtherProperty
  });
};

5. Define a pug to render component 5.定义一个用于渲染组件的哈巴狗

#my-element
  ul.my-list
    li(key='{something.id}', @repeat='something as someProperty')
      div(className='planet')  {something.name}
      div(className='vehicle')   {something.type}
      div(className='overview') {something.cost} 
      div(className='cancel', onClick='{()=> someOtherProperty(something)}')
        div(className='no-mobile fa fa-remove')

A read about my experience : https://medium.com/p/7610967954a 阅读我的经验: https//medium.com/p/7610967954a

With Pug, you have two options: render template to HTML string, passing the data object right away or render template to an efficient javascript function that outputs html when passed a data object. 使用Pug,您有两个选项:将模板渲染为HTML字符串,立即传递数据对象或将模板渲染到高效的javascript函数,该函数在传递数据对象时输出html。

When using pug(alone) with dynamic data, the choice is obviously to compile to function, so that data can be applied on the client. 当使用pug(单独)和动态数据时,显然选择编译为函数,以便可以在客户端上应用数据。

However, React does not actually consume, or send to the client, html. 但是,React实际上不会消耗或向客户端发送html。 If you read an explanation of JSX, you will see that it is just HTML-lookalike syntactic sugar that gets compiled to a javascript function that programmatically creates DOM nodes (essential for the way React handles diffing and updating the page). 如果您阅读了JSX的解释,您将看到它只是HTML-likealike语法糖被编译为javascript函数,以编程方式创建DOM节点(对于React处理差异和更新页面的方式至关重要)。 Pug at the moment, even on the client, outputs an HTML string. 目前,即使在客户端上,Pug也会输出一个HTML字符串。 Hence, the only way we will be able to use it is dangerouslySetInnerHTML as following: 因此,我们能够使用它的唯一方法是危险的SetInnerHTML ,如下所示:

 //from https://runkit.io/qm3ster/58a9039e0ef2940014a4425b/branches/master?name=test&pug=div%20Wow%3A%20%23%7Ba%7D%23%7Bb%7D function pug_escape(e){var a=""+e,t=pug_match_html.exec(a);if(!t)return e;var r,c,n,s="";for(r=t.index,c=0;r<a.length;r++){switch(a.charCodeAt(r)){case 34:n="&quot;";break;case 38:n="&amp;";break;case 60:n="&lt;";break;case 62:n="&gt;";break;default:continue}c!==r&&(s+=a.substring(c,r)),c=r+1,s+=n}return c!==r?s+a.substring(c,r):s} var pug_match_html=/["&<>]/; function pug_rethrow(n,e,r,t){if(!(n instanceof Error))throw n;if(!("undefined"==typeof window&&e||t))throw n.message+=" on line "+r,n;try{t=t||require("fs").readFileSync(e,"utf8")}catch(e){pug_rethrow(n,null,r)}var i=3,a=t.split("\\n"),o=Math.max(ri,0),h=Math.min(a.length,r+i),i=a.slice(o,h).map(function(n,e){var t=e+o+1;return(t==r?" > ":" ")+t+"| "+n}).join("\\n");throw n.path=e,n.message=(e||"Pug")+":"+r+"\\n"+i+"\\n\\n"+n.message,n}function test(locals) {var pug_html = "", pug_mixins = {}, pug_interp;var pug_debug_filename, pug_debug_line;try {;var locals_for_with = (locals || {});(function (a, b) {;pug_debug_line = 1; pug_html = pug_html + "\
    
    
    
      "; ;pug_debug_line = 1; pug_html = pug_html + "Wow: "; ;pug_debug_line = 1; pug_html = pug_html + (pug_escape(null == (pug_interp = a) ? "" : pug_interp)); ;pug_debug_line = 1; pug_html = pug_html + (pug_escape(null == (pug_interp = b) ? "" : pug_interp)) + "\<\/div\>";}.call(this,"a" in locals_for_with?locals_for_with.a:typeof a!=="undefined"?a:undefined,"b" in locals_for_with?locals_for_with.b:typeof b!=="undefined"?b:undefined));} catch (err) {pug_rethrow(err, pug_debug_filename, pug_debug_line);};return pug_html;} // pug source: "div Wow: #{a}#{b}" // this would obviously be much shorter if you include pug-runtime globally in your application function createMarkup(a,b) { return {__html: test({a:a,b:b})}; } function MyComponent(props) { return <div dangerouslySetInnerHTML={createMarkup(props.a, props.b)}/>; } ReactDOM.render( <MyComponent a="banana" b="&patata"/>, document.getElementById('root') ) 
     
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id=root /> 

Alternatively, there are attempts to translate jade or pug syntax into react directly, such as pug-react-compiler and babel-plugin-transform-pug-to-react . 或者,尝试将jade或pug语法直接转换为反应,例如pug-react-compilerbabel-plugin-transform-pug-to-react It seems they solved including further react components inside the pug template, which might be a desirable tradeoff for them possibly having quirks. 似乎他们解决了包括在哈巴狗模板内部的进一步反应组件,这可能是他们可能有怪癖的理想权衡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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