代码之家  ›  专栏  ›  技术社区  ›  Lee O.

我该怎么进口现代化产品呢?

  •  0
  • Lee O.  · 技术社区  · 7 年前

    我正在尝试检测浏览器是否支持Create React应用程序中的window.addEventListener。我按照Modernizer网站上的说明创建了一个modernizer.min.js文件,其中只包含我想要的单一功能测试。我不能导入现代化,因为它不是模块。这个小代码很难读取,所以我不确定在哪里修改它,使之成为一个模块。

    那么,如何在React应用程序的JavaScript中实际使用Modernizer呢?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Van    7 年前

    在你的下面 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>
    

    然后在代码中直接调用它

    即在 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
        } 
    
     ...
    

    如果你在用 打字稿 ,您需要首先在将使用modernizer的typescript文件的开头声明模块/对象,即。

    declare const Modernizr:any;
    

    或扩展 Window 接口,即

    declare global {
      interface Window {
        Modernizr:any     
      }
    }
    

    并称现代化为 window 像这样的界面

    window.Modernizr.someFeature