Using 'material-ui' with react-rails gem?

时间:2015-10-30 23:21:44

标签: ruby-on-rails reactjs asset-pipeline react-jsx react-rails

I would like to use the material-ui component library in my Rails 4 app. I am currently using the react-rails gem to add .jsx compilation to the asset pipeline. I have added material-ui via rails-assets in the gemfile like so:

source 'https://rails-assets.org' do
  gem 'rails-assets-material-ui'
end

And I have required the library in my application.js file like so:

//= require material-ui

However I keep getting the error "couldn't find file 'material-ui". How can I use the material-ui component library in my Rails app with the react-rails gem?

1 个答案:

答案 0 :(得分:15)

好的,这就是我到目前为止所做的工作......

到我添加的gemfile:

gem 'react-rails'
gem "browserify-rails"

这为我们提供了反应库,助手和jsx编译,以及使用require()sytax来获取JS中的模块的能力。 browserify-rails还允许我们通过package.json文件在您的Rails资产中要求npm模块。

我们可以通过这个package.json文件将material-ui库添加到我们的应用程序......

"dependencies" : {
    "browserify": "~> 10.2.4",
    "browserify-incremental": "^3.0.1",
    "material-ui": "0.13.1"
  },

材料ui库使用require语法以正确的顺序将所有不同的jsx组件文件连接在一起,这就是我们需要使用browserify-rails的原因。

接下来为了保持我们的反应代码在一起,我在asset / javascripts中创建了一个名为/ react ...的新目录。

react
    L /components
    L react.js
    L react-libraries.js
    L theme.js

现在作为'material-ui'依赖项的一部分,我们有了react库。这意味着目前我们有两个图书馆副本。一个来自'react-rails'宝石,另一个来自'material-rails'的'material-ui'库依赖。让我们使用'material-ui'依赖项中的那个,并从'react-rails'中保留一个。

在react.js中:

//= require ./react-libraries
//= require react_ujs
//= require_tree ./components

然后在react-libraries.js

//React Library
React = require('react');
//Material Design Library
MaterialUi = require('material-ui/lib');
injectTapEventPlugin = require('react-tap-event-plugin'); injectTapEventPlugin();
//Material Design Library Custom Theme
MyRawTheme = require('./theme');
ThemeManager = require('material-ui/lib/styles/theme-manager');

然后我们希望在资产管道中包含所有这些......

//= require react/react

在application.js。

现在您可以在/ react / components /中的jsx文件中编写组件 您可能还想使用...

命名组件
//Custom Components Namespace
Components = {};

in react-libraries.js

您可以在theme.js中自定义主题,如此...

Colors = require('material-ui/lib/styles/colors');
ColorManipulator = require('material-ui/lib/utils/color-manipulator');
Spacing = require('material-ui/lib/styles/spacing');

module.exports = {
  spacing: Spacing,
  fontFamily: 'Roboto, sans-serif',
  palette: {
    primary1Color: Colors.grey300,
    primary2Color: Colors.grey300,
    primary3Color: Colors.lightBlack,
    accent1Color: '#01A9F4',
    accent2Color: Colors.grey100,
    accent3Color: Colors.grey500,
    textColor: Colors.darkBlack,
    alternateTextColor: Colors.white,
    canvasColor: Colors.white,
    borderColor: Colors.grey300,
    disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3)
  }
};

希望有所帮助:)