javascript - 当反应应用程序未在 localhost:3000 上加载时,如何设置 webpack 和 babel
问题描述
我已经遵循了几个教程,但似乎都没有。我可以配置 webpack、babel 和一些简单的 React 组件,但它们没有在我的 localhost:3000 上呈现。关于我做错了什么的任何建议,因为终端中没有控制台日志或错误。
包.json
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"@babel/core": "^7.11.0",
"@babel/preset-env": "^7.11.0",
"@babel/preset-react": "^7.10.4",
"babel-loader": "^8.1.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-hot-loader": "^4.12.21",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}
}
.babelrc
{
"presets":
[
"@babel/preset-env",
"@babel/preset-react"
]
}
webpack.config.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
devtool: 'inline-source-map',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist',),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
port: 3000,
contentBase: './dist',
hot: true
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
};
索引.html
<!DOCTYPE html>
<html>
<head>
<title>My React Configuration Setup</title>
</head>
<body>
<div id="root"></div>
<!-- <script src="./dist/bundle.js"></script> -->
</body>
</html>
index.js
import React from "react";
import ReactDOM from "react-dom";
import Welcome from './App'
ReactDOM.render(<Welcome />, document.getElementById("root"));
module.hot.accept();
应用程序.js
import React from 'react';
class Welcome extends React.Component {
render() {
return <h1>Hello World from React boilerplate</h1>;
}
}
export default Welcome
解决方案
你快到了。
bundle.js
使用下面webpack
的命令构建package.json
"scripts": {
"start": "webpack && webpack-dev-server --mode development",
"test": "echo \"Error: no test specified\" && exit 1"
},
或者
"scripts": {
"build": "webpack",
"start": "webpack-dev-server --mode development",
"test": "echo \"Error: no test specified\" && exit 1"
},
- 修改
webpack.config.js
contentBase
属性,因为你的index.html
叶子在根(你可以将它移动到dist
)
devServer: {
port: 3000,
contentBase: './',
hot: true
},
- 取消注释
bundle.js
导入index.html
:
<div id="root"></div>
<script src="./dist/bundle.js"></script>
</body>
你可以用它create-react-app
来非常快地初始化一个空的 React 项目
推荐阅读
- memory-management - 我无法解释这个图:“内存泄漏”与否?
- ruby-on-rails - 在不同端口上运行多个 Rails 应用程序的问题
- python - 如何修复“元组”对象没有“层”属性?
- ios - UITableView - reloadRows 方法创建奇怪的滚动错误
- ramda.js - 如何改进我编写的 ramda 代码?
- c# - 多个 DbContexts 但在使用 Azure DevOps 部署时只有一个在运行
- vagrant - 无法通过 192.168.10.10 访问 Windows 10 上的 Homestead
- powershell - 如何安装 AzureAD PowerShell 模块
- c# - 根据返回查询映射两个相同的模型
- swift - BluetoothLE 会扰乱定时器计时吗?