search
HomeWeb Front-endHTML Tutorial异步加载非核心 CSS_html/css_WEB-ITnose

在生产环境中如果依靠前端引用JSXTransformer.js文件来实现JSX向JavaScript的转换,那是绝对不靠谱的。所以,使用Reactjs的童鞋就需要使用更有逼格的方式来完成这项任务。作为现在最常用的前端构建工具gulp搭配上Browserify来搞定这个问题那真是拉风的不要不要的 :)

废话不多说,咱们来点直接的吧。

源代码

我们这次的任务就是让这段满目疮痍的源代码变得更优化,千里之行,这是开始。如果有童鞋看不懂这段代码是用来做神马的,那么我只能说,“妈妈叫你回家看基础了。” 回家之路 (看不懂代码的,请猛戳)。

<div id="app"></div><script type="text/jsx">	var HelloWorld = React.createClass({ 		render: function() { 			return (				<div> Hello World </div> 			);		}	}); 	React.render(<HelloWorld />, document.getElementById('app'));</script><script type="text/jsx">	var Child = React.createClass({ 		render: function() { 			return (				<div> The Child </div> 			);		}	}); 	var Parent = React.createClass({ 		render: function() { 			return (				<div> Hello World </div>				<Child/> 			); 		} 	}); 	React.render(<Parent />, document.getElementById('app'));</script>

优化

前面把两个组件都写到一块了,现在来分割成独立的文件。其中一个命名为js/components/Parent.jsx,内容如下:

var Child = require('./Child.jsx');var Parent = React.createClass({  render: function(){    return (      <div>        <div> Hello World </div>        <Child/>      </div>    )  }});module.exports = Parent;

Parent 的子元器件Child写到js/components/Child.jsx中,内容如下:

var Child = React.createClass({  render: function(){    return (      <div> The Child </div>    )  }});module.exports = Child;

写到这里,我们已经将两个组件做了初步的拆分,如果有童鞋对module.exports是神马还是一知半解或者根本不懂这是要搞什么飞机,那么请去百度自行谷歌CMD规范,相信度娘会很妩媚的帮你解惑。

如果要真正让元器件显示在页面上需要执行React.render函数,这个是写在js/app.js中的,内容如下:

var Parent = require('./components/Parent.jsx');React.render(<Parent />, document.getElementById('app'));

做到这里,我们还顺带了做了一件很有意义的事情,就是对文件文件目录做了优化,组件放置在/components文件夹中,启动放置在根目录/js下,清晰明了。

使用Browerify之后,html文件中只需要引入一个自定义script文件就好了 ,如下:

<script src='js/bundle.js'></script>

所有依赖的js内容未来都会被编译到bundle.js文件中。

安装 Browserify

首先要安装 Gulp 。这里我假设大家的系统上都安装好了 nodejs 并且也全局安装了 gulp ,也就是敲gulp -v
是可以看到输出的。

首先确认你的电脑已经成功安装了gulp,至于怎么安装,这我就不多说了。去谷歌百度一下会是一个好办法。

如果你在命令行敲击如下命令

gulp -v

输出结果大概如下面这个这样子的话,那就说明你已经成功安装了gulp。

CLI version 3.9.0Local version 3.9.0

在这个基础上,进入项目目录还需要来局部安装 gulp ,browserify 以及相关的辅助工具:

npm install --save-dev gulp browserify vinyl-source-stream babelify

使用Mac的童鞋不要忘记加sudo哟。

说一下上面四个包的各自作用:

  • gulp 是任务运行环境,用来进行任务调度

  • browserify 用来 require js 的模块

  • vinyl-source-stream 把 browserify 输出的数据进行准换,使之流符合 gulp 的标准

  • reactify 使用它来实现 JSX 编译功能

然后到 gulpfile.js 中,填写如下内容:

var gulp = require("gulp"),	browserify = require('browserify'),	reactify = require('reactify'),	source = require('vinyl-source-stream');gulp.task('jsx', function() {	browserify('./js/app.js')		.transform(reactify)		.bundle()		.pipe(source('bundle.js'))		.pipe(gulp.dest('js'));});

来解释一下上面的脚本流程。首先就是把入口文件 app.js 交给 browserify 进行处理,对于 jsx 的编译,官方推荐使用的就是reactify。下一步,运行 bundle()来把所有依赖都打包成 bundle.js ,但是注意,browserify 不是一个专门为 gulp 写的包,所有它输出的数据流并不能直接 pipe 给 gulp 使用,所以,需要用到 source()接口,也就是 vinyl-source-stream 这个工具来处理一下,然后 pipe 给 gulp ,gulp.dest 会把输出的 bundle.js 文件保存到 js 文件夹中。

任务写好了,在命令行执行:

gulp jsx

这样就生成了 js/bundle.js 文件了。由于这个文件的标签已经添加到 index.html 中了,所以直接用 chrome 打开就可以看到运行效果了。

文章改编自 《当 React 遇见 Gulp 和 Browserify》

原文 http://segmentfault.com/a/1190000004002631
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.