Home  >  Article  >  Web Front-end  >  What to do if require in react fails

What to do if require in react fails

藏色散人
藏色散人Original
2023-01-03 10:38:371926browse

The require in react fails because require returns an ES module instead of a string. The solution is to introduce it through "require('../path/to/image.jpg').default;" That’s it.

What to do if require in react fails

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

What should I do if require in react fails?

The reasons and solutions for invalid images introduced by require in the react project

Cause

If you use create-react-app and require to import Image, require returns an ES module instead of a string. This is because in file-loader, the esModule option is enabled by default.

Solution

const image = require('../path/to/image.jpg').default;
// OR
import image from '../path/to/image.jpg';

The difference between require and import

require is the specification of commonjs, the API implemented in node; Import is the syntax of es and is processed by the compiler. Therefore, import can do static analysis of module dependencies, and can do treeshaking with webpack, rollup, etc.

The value exported by commonjs will be copied. require introduces the copied value (reference types only copy the reference). The value exported by es module is the same (excluding export default), regardless of the basic type. or application type.

There are differences in writing methods. For import, you can use import * to introduce all exports, or you can use import aaa, {bbb} to introduce default and non-default exports respectively, which is more flexible than require.

Recommended learning: "react video tutorial"

The above is the detailed content of What to do if require in react fails. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn