gpt4 book ai didi

javascript - React 和 ReactDOM 未使用 webpack、babel 加载

转载 作者:行者123 更新时间:2023-12-03 02:02:13 25 4
gpt4 key购买 nike

我正在使用 webpack 和 babel 设置 React 项目,但收到React 和 ReactDOM 无法解析的错误。

问题是出在Webpack还是Babel的版本上吗?

PS C:\Users\abhi\Desktop\mern-app> npm run webpack

> mern-app@1.0.0 webpack C:\Users\abhi\Desktop\mern-app
> webpack

ERROR in ./app.js
Module not found: Error: Can't resolve 'react' in 'C:\Users\abhi\Desktop\mern-app'
@ ./app.js 5:13-29

ERROR in ./app.js
Module not found: Error: Can't resolve 'react-dom' in 'C:\Users\abhi\Desktop\mern-app'
@ ./app.js 9:16-36
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! mern-app@1.0.0 webpack: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the mern-app@1.0.0 webpack script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\abhi\AppData\Roaming\npm-cache\_logs\2018-04-21T14_25_50_508Z-debug.log

配置和文件如下

package.json

{
"name": "mern-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"webpack": "webpack"
},
"author": "Abhishek Kulshrestha",
"license": "ISC",
"dependencies": {
"npm": "^5.8.0",
"react": "^16.3.2",
"react-dom": "^16.3.2"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^4.6.0",
"webpack-cli": "^2.0.15"
}
}

webpack.config.js

var path = require('path');

var webpack = require('webpack');

module.exports ={
entry:'./app.js',
output:{
filename:'bundle.js',
path:__dirname
},
resolve:{
extensions:['.js']
},
module:{
rules:[{
test:/.jsx?$/,
use:{
loader:'babel-loader',
options:{
presets: ['env',
'react']
}
},
exclude:/.node_modules/

}]
}

}

app.js

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component{
render(){
return '<h1>Hello </h1>'
}
}

ReactDOM.render(<App/>,document.getElementById('app'));

所有文件(package.json、webpack.config.js、app.js、index.html)都位于同一主文件夹中

请帮忙

最佳答案

这段代码对我来说看起来不错。我认为您在运行 webpack 命令之前错过了依赖项安装步骤。

请尝试按顺序执行以下步骤,看看是否可以解决该错误。

  1. 在目录内运行 npm install,这将确保您在 package.json 中提到的所有依赖项都下载到 node_modules 目录。
  2. 然后运行npm run webpack生成bundle.js

关于javascript - React 和 ReactDOM 未使用 webpack、babel 加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49956964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com