利用webpack创建react项目

96 阅读1分钟

1.创建项目文件夹  mkdir my-app

2.进入该目录文件夹  cd my-app

3.然后在my-app目录下创建src文件夹用来存放React代码 mkdir src

4.使用npm命令初始化项目 npm init -y

5.安装项目所需要的插件  npm install webpack webpack-cli @babel/core babel-loader @babel/preset-env @babel/preset-react  react react-dom --save-dev

6.安装成功后,在my-app根目录创建.babelrc文件,然后写入以下配置

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

另还需配置webpack,在my-app根目录创建webpack.config.js,写入以下配置

const path = require('path');

module.exports = {
  entry: './src/main.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};

7.在src目录下新建三个文件index.html、main.js、App.js,接下来因为webpack默认只能对.js文件进行最终打包,而我们的项目是有.html文件的,所以我们必须下载和html有关的loader和插件来对html进行处理。

npm install html-webpack-plugin html-loader --save-dev

安装完成后需要在webapck.config.js进行配置

const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
  entry: './src/main.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.html$/,
        use: {
          loader: 'html-loader'
        }
      }
    ]
  },
  plugins: [
    new HtmlWebPackPlugin({
      titel: 'react app',
      filename: 'index.html',
      template: './src/index.html'
    })
  ]
};

8.配置完成后,在index.html文件中写入以下代码,最基本的html页面代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>React</title>
</head>
<body>
  <div id="app"></div>
</body>
</html>

在App.js文件创建一个组件并导出

import React from 'react'

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

export  default App

在main.js文件导入该组件并渲染

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App.js'

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

至此一个react项目就创建成功了

9.运行该项目,运行之前还要安装webpack-dev-server用来启动一个本地服务器来浏览我们的项目并且可以实现保存自动刷新  npm install webpack-dev-server --save-dev

然后在package.json文件写入以下配置

"scripts": {
    "start": "webpack-dev-server --open --mode development"
}

10.最后 npm run start就可以在浏览器中看到Hello World了