Material Design Lite with ReactJS (import/require Issue)

亡梦爱人 提交于 2019-12-02 01:08:08

I figured out the solution myself. There are two ways through which you can achieve this.

The Lazy Way

In node_modules/material-design-lite/material.js, edit & add the following code in the end as mentioned below.

// You can also export just componentHandler
if (typeof module === 'object') {
  module.exports = window;
}

Your material.js file will look like this.

;(function() {
  .
  .
  .
  componentHandler.register({
    constructor: MaterialRipple,
    classAsString: 'MaterialRipple',
    cssClass: 'mdl-js-ripple-effect',
    widget: false
  });

  // You can also export just componentHandler
  if (typeof module === 'object') {
    module.exports = window;
  }

}());

In your React Component file, require like this,

var MDLite = require('material-design-lite/material');
var componentHandler = MDLite.componentHandler;

Then, you can call componentHandler.upgradeDom() to upgrade MDL elements.

Note that you can also write module.exports = componentHandler; if you only want to import componentHandler.

The Webpack Way

Personally, I would prefer the webpack way as it is much cleaner & you need not to edit the module files yourself.

Install exports-loader, npm install exports-loader --save-dev. Then, in your webpack.config.js, specify loaders as

loaders: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    loader: 'exports-loader!babel-loader'
  }
]

In your React Component file, you can require componentHandler as

var componentHandler = require('exports?componentHandler!material-design-lite/material');

I hope it helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!