从零开始配置webpack react开发环境

首先初始化项目

npm init

一、安装webpack

要安装最新版本或特定版本,请运行以下命令之一:

npm install --save-dev webpack
npm install --save-dev webpack@

如果你使用 webpack 4+ 版本,你还需要安装 CLI。

npm install --save-dev webpack-cli

二、新建文件目录

mkdir ./src ./public ./src/components
vim ./src/index.js
vim ./src/components/HellowWord.js
vim ./public/index.html


# 文件目录格式
|-- Webpack
    |-- package-lock.json
    |-- package.json
    |-- webpack.config.js
    |-- public
    |-- src
        |-- index.js



  
// src/index.js
import React from "react";
import HelloWorld from "./components/HellowWorld";

class App extends React.Component {
  render() {
    return ;
  }
}

ReactDOM.render(, document.getElementById("app"));
// src/components/HelloWorld.js

import React from "react";

export default class App extends React.Component {
  render() {
    return 

Hello World

; } }

三、配置加载器

3.1 构建简单的webpack.common.js配置文件

根据上述文件目录结构,新建配置文件 public/webpack.common.js

const path = require("path");
const webpack = require("webpack");

function resolve(dir) {
  return path.join(__dirname, "..", dir);
}

module.exports = {
  entry: "./src/index.js",
  output: {
    path: util.resolve("dist"),
    filename: "[name].js",
    chunkFilename: "[chunkhash].js",
    jsonpFunction: "myWebpackJsonp"
  }
};

packge.json添加

"scripts": {
  "dev": "webpack --config ./build/webpack.common.js"
},

尝试运行npm run dev

ERROR in ./src/index.js 7:11
Module parse failed: Unexpected token (7:11)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| class App extends React.Component {
|   render() {
>     return ;
|   }
| }

webpack告诉我们需要使用加载器来处理该文件,针对 react 文件,需要使用babel-loader,对于其他的格式文件,需要进行配置。

由于配置中会用到一些工具,所以新建/build/util.js,引入util.js

const path = require("path");

//返回项目根目录下的dir路径
exports.resolve = function resolve(dir) {
  return path.join(__dirname, "..", dir);
};

//返回dits中文件路径下的dir路径
exports.staticPath = function resolve(dir) {
  return path.join("static/", dir);
};

3.2 配置babel-loader

npm install -D babel-loader @babel/core @babel/preset-env @babel/preset-react

webpack.config.js添加 babel 配置

...

module: {
  rules: [
    {
      test: /\.js?$/,
      include: [util.resolve('src')],
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env', '@babel/preset-react']
        }
      }
    }
  ]
}
...

3.3 配置.css .scss文件 loader

  • sass-loader
  • css-loader
  • style-loader

sass-loader依赖node-sass,由于这个包存放在 github 上,下载速度比较慢,可使用淘宝源下载

npm install sass-loader node-sass css-loader style-loader --save-dev --registry https://registry.npm.taobao.org

webpack.config.jsrules 添加配置

...

  {
    test: /\.css$/,
    use: [{ loader: "style-loader" }, { loader: "css-loader" }]
  },
  {
    test: /\.scss$/,
    use: [
      { loader: "style-loader" }, // 将 JS 字符串生成为