webpack搭建React
1. 全局安装Webpack, Babel, Webpack-dev-server:
npm install babel webpack webpack-dev-server -g
2..建立项目目录,用npm init 初始化 npm 项目
mkdir react-hello-world
cd react-hello-world
npm init
The CLI moved into a separate package: webpack-cli. Please install 'webpack-cli' in addition to webpack itself to use the CLI. -> When using npm: npm install webpack-cli -D -> When using yarn: yarn add webpack-cli -D
3.注:执行npm init命令时会让你输入各种项目信息,一般直接回车就好,会自动填写默认值。但是,要注意name不能跟我们的模块和项目文件目录同名。
初始化时也可以使用以下命令:
npm init -yes
5.在项目中安装 react, react-dom
npm install react react-dom --save
6.在项目中安装 Babel 转换器,需要用到插件 babel-preset-react, babel-preset-latest,latest 即最新的 ES 规范,包括了 Async/Await 这些新特性。
npm install babel-loader babel-core babel-preset-react babel-preset-latest --save
7.创建项目文件,main.js 即项目入口文件,App.js 即 React 组件主文件
touch index.html App.js main.js webpack.config.js
8.配置webpack,编辑webpack.config.js
module.exports = {
entry: './main.js',// 入口文件路径
output: {
path: '/',
filename: 'index.js'
},
devServer: {
inline: true,
port: 3001 },
module: {
loaders: [
{
test: /\.js$/,// babel 转换为兼容性的 jsexclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'latest']
}
}
]
}
}
9.开始项目编写 index.html
<body>
<div id="app"></div>
<script src="index.js"></script>
</body>
10.app.js
import React from 'react';class App extends React.Component { render() { return
Hello World!
}}
export default App
11. main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(, document.getElementById('app'));
12. 配置 npm scripts, 编辑 package.json,在"scripts"属性处添加一行:
"scripts": {
"start": "webpack-dev-server"
},