如何在 React 中导入 Modernizr

Lee*_* O. 3 modernizr reactjs

我正在尝试检测浏览器是否支持 create-react-app 中的 window.addEventListener。我按照 Modernizr 网站上的说明创建了一个 Modernizr.min.js 文件,其中只包含我想要的单个功能测试。我无法导入 Modernizr,因为它不是一个模块。缩小后的代码很难阅读,所以我不确定在哪里修改它以使其成为模块。

那么我如何在 react app 的 javascript 中实际使用 Modernizr 呢?

Van*_*Van 6

在你public/index.html刚才直接导入脚本

公共/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
    <meta name="theme-color" content="#000000" />


    ...


    <!-- add your scripts here -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
    <!-- -->


    <title>React App</title>
  </head>
  <body>
Run Code Online (Sandbox Code Playgroud)

然后在你的代码中直接调用它

即在App.jsx

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {

    // add this to not trigger eslint no-undef
    /* global Modernizr */
    console.log(Modernizr);
    // do your checking with Modernizr
    if (Modernizr.awesomeNewFeature) {
      // do your stuff here
    } 

 ...
Run Code Online (Sandbox Code Playgroud)

如果您使用的是typescript,则需要首先在将使用 Modernizr 的 typescript 文件的开头声明模块/对象,即

declare const Modernizr:any;
Run Code Online (Sandbox Code Playgroud)

或扩展Window接口,即

declare global {
  interface Window {
    Modernizr:any     
  }
}
Run Code Online (Sandbox Code Playgroud)

window像这样在界面下调用 Modernizr

window.Modernizr.someFeature
Run Code Online (Sandbox Code Playgroud)