I'm trying to detect whether the browser supports window.addEventListener in a create-react-app. I followed the instructions on the modernizr website and have created a modernizr.min.js file with only the single feature test I want. I can't import modernizr since it's not a module. The minified code is hard to read so I'm not sure where I'd modify it to make this a module.
So how do I actually use Modernizr in the javascript of react app?
Under your public/index.html
just import the script directly
public/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>
And then in your code just call it directly
i.e. in 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
}
...
If you're using typescript, you need to declare the module/object first in the beginning of the typescript file that will use Modernizr, i.e.
declare const Modernizr:any;
or extend the Window
interface, i.e.
declare global {
interface Window {
Modernizr:any
}
}
and call Modernizr under window
interface like so
window.Modernizr.someFeature