当前位置: 代码迷 >> 综合 >> requirejs+jsx再会
  详细解决方案

requirejs+jsx再会

热度:102   发布时间:2023-09-13 01:17:20.0

上回项目优化中,原本是jsx文件,那么如果直接使用 jsx语法,应该也是可以的。在简书上还正好有一文章,https://www.jianshu.com/p/138b5b7b0a36,可是没跑起来,可能还是缺什么资源了。

不过从本文描述,提到了一个重要库requirejs-react-jsx,于是就在本地,按照https://npm.taobao.org/package/requirejs-react-jsx这个上面的example试着运行,直接拷贝下来肯定不行。

先来看看jsx语法定义的amd模块

component.jsdefine(['react'
],function(React){return React.createClass({render:function(){return(<div>I am jsx component</div>);}})
});app.js
注意这里的jsx!,这是必须要的,否则不能用jsx语法define(["react","jsx!js/component","jsx!js/multi"],function(React,Component,Multi){function App() {this.AppView = React.createClass({render: function () {return (<div><Component /><p>Hello world,hello React!</p></div>);}});}App.prototype.init = function () {React.render(<this.AppView />, document.body);};return App;});

另外 requirejs支持一个文件里定义多个模块,每个模块必须有name.

multi.jsdefine('one', function(){//console.log("i am one");function showme(){console.log("i am one");}return{showme:showme}
});define('two', function(){//  console.log("i am two");function showme(){console.log("i am two");}return{showme:showme}
});

然后只要在页面上引用 multi.js,就可以在app.js如下访问

注意这里的one,two是模块名require(['one','two'],function(one,two){console.log(one,two);});

项目的代码已经上传
git地址

另外这里说下,关于require.js加载commonjs模块一说http://requirejs.org/docs/api.html#packages 如下实现

card/main.jsexports.app = function(){console.log('Im an application!');
}
requirejs+jsx再会
image.png

并不能成功加载。

github上的一个问题
How to load commonjs module from requirejs, document not describe clearly

要想被requirejs加载,可以通过

node r.js -convert path/to/commonjs/modules/ path/to/output
进行转化

或者进行封装如下

define(function(require, exports, module) {//Put traditional CommonJS module content here
});

下面是该文https://addyosmani.com/writing-modular-js/提到的requirejs amd模块的优点

  • Provides a clear proposal for how to approach defining flexible modules.
  • Significantly cleaner than the present global namespace and <script> tag solutions many of us rely on. There's a clean way to declare stand-alone modules and dependencies they may have.
  • Module definitions are encapsulated, helping us to avoid pollution of the global namespace.
  • Works better than some alternative solutions (eg. CommonJS, which we'll be looking at shortly). Doesn't have issues with cross-domain, local or debugging and doesn't have a reliance on server-side tools to be used. Most AMD loaders support loading modules in the browser without a build process.
  • Provides a 'transport' approach for including multiple modules in a single file. Other approaches like CommonJS have yet to agree on a transport format.
  • It's possible to lazy load scripts if this is needed.