npm与巴贝尔和webpack创build反应应用程序不起作用
我是新兴的UI技术。 我正在尝试我的手在reactjs随着webpack和babel我创build了一个应用程序后使用npm安装它使用create-react-app插件。 我进入src文件夹并执行npm start,启动浏览器并显示演示页面。 我试图添加babel和webpack到这个演示,但不幸的是它不工作。 我打开浏览器中的index.html页面,它不显示我所遵循的jsx文件内容https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-的WebPack-du107r9zr
我不知道为什么这不起作用,可以请一些帮助吗?
index.jsx
import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { render () { return <p> Hello React!</p>; } } render(<App/>, document.getElementById('app'));
的index.html
<html> <head> <meta charset="utf-8"> <title>React.js using NPM, Babel6 and Webpack</title> </head> <body> <div id="app" /> <script src="public/bundle.js" type="text/javascript"></script> </body> </html>
.babelrc文件
{ "presets" : ["es2015", "react"] }
webpack.config.js文件
var webpack = require('webpack'); var path = require('path'); var BUILD_DIR = path.resolve(__dirname, 'src/client/public'); var APP_DIR = path.resolve(__dirname, 'src/client/app'); var config = { entry: APP_DIR + '/index.jsx', output: { path: BUILD_DIR, filename: 'bundle.js' }, module : { loaders : [ { test : /\.jsx?/, exclude : /(node_modules)/, include : APP_DIR, loader : 'babel-loader' } ] } }; module.exports = config;
create-react-app
命令在场景后面create-react-app
一些有趣的事物。 我将强调一些命令, start
和build
。
start
,为您运行开发环境。 每次更改文件时都会重新编译。 类似于nodemon
中的nodemon。
build
这将编译你的反应文件到一个缩小版本,基本上工作相同的webpacks
。
因此不需要安装webpack
或babel
。
你需要安装babel来编译你的es6并作出反应
做它使用
C:\Users\username\Desktop\reactApp>npm install babel-core C:\Users\username\Desktop\reactApp>npm install babel-loader C:\Users\username\Desktop\reactApp>npm install babel-preset-react C:\Users\username\Desktop\reactApp>npm install babel-preset-es2015 C:\Users\username>npm install -g babel C:\Users\username>npm install -g babel-cli
尽量保持我们的webpack为
var config = { entry: './todoApp.js', output: { path:'./', filename: 'index.js', }, devServer: { inline: true, port: 9191 }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ], loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ] } } module.exports = config;
你需要改变你的渲染导入
var ReactDOM=require('react-dom');
然后用它作为
ReactDOM.render
将webpack添加到它只需使用npm全局安装webpack
npm install webpack --save npm install webpack -dev-server --save
为了更多的帮助遵循这个reactjs设置
Create-react-app使用webpack和babel。 它已经融入了这个项目。 如果您想手动修改create react应用程序的默认configuration,即将事件添加到您的webpackconfiguration中,而这些configuration不是使用create-react-app本地创build的,那么您将需要运行npm run eject
以分离内部从控制它们的react-scripts包进行configuration。 合理?