Javascript 如何使用 Typescript 为 React 设置 Material-UI?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37186500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:00:27  来源:igfitidea点击:

How to setup Material-UI for React with Typescript?

javascriptreactjstypescriptmaterial-ui

提问by René Stalder

I've run in some problems add Material UI to my React project, which is programmed with Typescript.

我在将 Material UI 添加到我的 React 项目中遇到了一些问题,该项目是用 Typescript 编程的。

According to the tutorial, I start with adding the react-tab-event-plugin first.

根据教程,我首先添加 react-tab-event-plugin 。

import injectTapEventPlugin from 'react-tap-event-plugin';

// Needed for onTouchTap
// Can go away when react 1.0 release
// Check this repo:
// https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

Doing this, I get an error about the missing default export.

这样做时,我收到有关缺少默认导出的错误消息。

ERROR in ./src/index.tsx
(4,8): error TS1192: Module ''react-tap-event-plugin'' has no default export.

Adding Material UI

添加材质 UI

import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

Throws following build error

引发以下构建错误

ERROR in ./src/containers/index.tsx
(8,25): error TS2307: Cannot find module 'material-ui/styles/getMuiTheme'.

ERROR in ./src/containers/index.tsx
(9,30): error TS2307: Cannot find module 'material-ui/styles/MuiThemeProvider'.

My Webpack Config is quite easy and did work with every React npm modul when I added the typings, until now.

我的 Webpack Config 非常简单,并且在我添加类型时确实适用于每个 React npm 模块,直到现在。

var cssnext = require('postcss-cssnext')
var postcssImport = require('postcss-import')
var ExtractTextPlugin = require('extract-text-webpack-plugin')

// noinspection JSUnresolvedVariable
module.exports = {
  entry: {
    app: './src/index.tsx',
    lib: [
      './node_modules/react/react.js',
      './node_modules/react-dom',
      './node_modules/normalize.css/normalize.css'
    ]
  },
  output: {
    path: './dist',
    filename: '[name].js'
  },
  devtool: 'source-map',
  devServer: {
    contentBase: '/dist/',
    inline: true,
    port: 3333,
    host: '0.0.0.0'
  },
  resolve: {
    // Add `.ts` and `.tsx` as a resolvable extension.
    extensions: [ '', '.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.css', '.html' ],
    modulesDirectories: ['src', 'node_modules']
  },
  module: {
    loaders: [
      // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
      { test: /\.ts(x?)$/, loader: 'babel-loader!ts-loader' },
      { test: /\.html$/, loader: 'file?name=[name].[ext]' },
      { test: /\.json$/, loader: 'json' },
      { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader') }
    ],
    preLoaders: [
      // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
      { test: /\.js$/, loader: 'source-map-loader' }
    ]
    /*    loaders: [
     {
     test: /\.js$/,
     exclude: /node_modules/,
     loader: 'babel-loader!ts-loader',
     query: {
     presets: [
     'es2015',
     'react'
     ]
     }
     }
     ]*/
  },
  plugins: [
    new ExtractTextPlugin('[name].css', {
      allChunks: true
    })
  ],
  postcss: function (webpack) {
    return [
      postcssImport({
        addDependencyTo: webpack
      }),
      cssnext({
        browsers: 'last 2 versions, ie >= 9'
      })
    ]
  }
  // When importing a module whose path matches one of the following, just
  // assume a corresponding global variable exists and use that instead.
  // This is important because it allows us to avoid bundling all of our
  // dependencies, which allows browsers to cache those libraries between builds.
  /*
   externals: {
   'react': 'React',
   'react-dom': 'ReactDOM'
   }
   */
}

Typing for both, react-tap-event-plugin and Material-UI are installed.

为两者打字,安装了 react-tap-event-plugin 和 Material-UI。

What's wrong?

怎么了?

回答by René Stalder

@types/material-uiis now available, exported from its DefinitelyTyped source.

@types/material-ui现在可用,从其绝对类型源导出。

npm install @types/material-ui --save-dev

npm install @types/material-ui --save-dev

npm install @types/react-tap-event-plugin --save-dev

npm install @types/react-tap-event-plugin --save-dev

Afterwards, you can do following:

之后,您可以执行以下操作:

import * as injectTapEventPlugin from 'react-tap-event-plugin';

// Needed for onTouchTap
// Check this repo:
// https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

Then use Material UI like this:

然后像这样使用 Material UI:

import * as React from 'react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {MuiThemeProvider, lightBaseTheme} from "material-ui/styles";

const lightMuiTheme = getMuiTheme(lightBaseTheme);

class Root extends React.Component<any, any> {
  render() {
    return (
      <MuiThemeProvider muiTheme={lightMuiTheme}>
        <MyComponent/>
      </MuiThemeProvider>
    )
  }
}

The MyComponent would consume Material UI as defined in the docs:

MyComponent 将使用文档中定义的 Material UI:

import RaisedButton from 'material-ui/RaisedButton';

const MyComponent = (props:MyComponentProps) => {
  return (
      <RaisedButton label="Default" />
  )
}

export default MyComponent;

2016-08-08:Answer updated due to state change of the package.

2016-08-08:由于包的状态变化而更新了答案。

2017-01-03:Add ref. to @types /qvazzler

2017-01-03:添加参考。到@types /qvazzler

回答by bhish

Types are now bundled directly with Material-ui so there is no need to install @types/material-ui package.

类型现在直接与 Material-ui 捆绑在一起,因此无需安装@types/material-ui package.

Instead you can just install the @material-ui/corepackage as normal and it should work.

相反,您可以@material-ui/core像往常一样安装软件包,它应该可以工作。

See the official Material-UI + Typescript example with create react app here: https://github.com/mui-org/material-ui/tree/master/examples/create-react-app-with-typescript

在此处查看带有 create react app 的官方 Material-UI + Typescript 示例:https: //github.com/mui-org/material-ui/tree/master/examples/create-react-app-with-typescript

回答by neo post modern

Your commentalready pointed out the core problem. The typings are not up-to-date, or in other words: completely off.

您的评论已经指出了核心问题。类型不是最新的,或者换句话说:完全关闭。

Long story short, it seems like the structure of material-uihas changed and everything is camelcase (instead of dashes) and in root, not the libfolder now.

长话短说,似乎结构material-ui已经改变,一切都是驼峰式(而不是破折号)和根目录,而不是lib现在的文件夹。

To fix this, open your material-ui/index.d.tsfile and start changing everything from

要解决此问题,请打开您的material-ui/index.d.ts文件并开始更改所有内容

declare module 'material-ui/lib/text-field' {

to

declare module 'material-ui/TextField' {

If unsure, check your node_modules/material-uifolder to see the file structure. The ambient module name mustmatch the underlying file structure.

如果不确定,请检查您的node_modules/material-ui文件夹以查看文件结构。环境模块名称必须与底层文件结构匹配。

This probably won't fix all your problems, but it could be a start.

这可能不会解决您的所有问题,但它可能是一个开始。

回答by Ratnesh Chauhan

Add these two dependencies to your package.json file and run npm install and then start. It worked for me

将这两个依赖项添加到您的 package.json 文件并运行 npm install 然后启动。它对我有用

"@types/material-ui": "^0.21.1", "material-ui": "^0.20.0",

"@types/material-ui": "^0.21.1", "material-ui": "^0.20.0",