React: Deep requiring is deprecated as of uuid, Please require the top-level module

拜拜、爱过 提交于 2020-07-09 04:29:08

问题


my React app successfully shows the button however receiving this error.

index.js:1 Deep requiring like const uuidv4 = require('uuid/v4'); is deprecated as of uuid@7.x. Please require the top-level module when using the Node.js CommonJS module or use ECMAScript Modules when bundling for the browser

import React, { Component } from 'react';
import { Container, ListGroup, ListGroupItem, Button } from 'reactstrap';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import uuid from 'uuid/v4';

class ShoppingList extends Component {
    state = {
        items: [
            { id: uuid(), name: 'Eggs' },
            { id: uuid(), name: 'Milk' },
            { id: uuid(), name: 'Steak' },
            { id: uuid(), name: 'Water' },
        ]
    }

    render() {
        const { items } = this.state;
        return (
            <Container>
                <Button 
                 color="dark"
                 style={{marginBottom: '2rem'}}
                 onClick={() => {
                    const name = prompt('Enter Item');
                    if (name) {
                        this.setState(state => ({
                           items: [...state.items, { id: uuid(), name }] 
                        }));
                    }
                }}
                >Add Item</Button>
            </Container>
        );
    }
}

export default ShoppingList;
  • I tried to use 'import { v4 as uuidv4 } from 'uuid'; uuidv4();'
  • however my button would not show up and i would get error:
  • Uncaught ReferenceError: uuid is not defined
  • Perhaps i am meant to be getting this error? and everything is currently working fine?

回答1:


You can use react-uuid instead

npm i react-uuid

usage

import uuid from "react-uuid";

Try it online:




回答2:


This has changed after recent update to library and now you may import uuid, as per library description :

"As of uuid@7 this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the import"

import { v4 as uuid_v4 } from "uuid";
uuid_v4()

... or for CommonJS:

const { v4: uuid_v4 } = require('uuid');
uuid_v4();


来源:https://stackoverflow.com/questions/60721008/react-deep-requiring-is-deprecated-as-of-uuid-please-require-the-top-level-mod

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