React 脱离脚手架

2019-07-09  本文已影响0人  caiyiii

React脱离脚手架配置webpack

1.项目初始化

yarn init -y

2.安装生产依赖

yarn add react --save
yarn add react react-dom --save

3.安装开发依赖

yarn add webpack -D
yarn add webpack-cli -D
yarn add webpack-dev-server -D
yarn add style-loader -D
yarn add sass-loader -D
yarn add loader-sass -D
yarn add url-loader -D 
yarn add html-webpack-plugin -D
yarn add copy-webpack-plugin -D

4.构建目录结构

项目目录大致结构.png

5.配置webpack

  1. 配置基本环境 => webpack.base.conf.js文件
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");

module.exports = {
  // 入口
  entry: path.resolve(__dirname, "../src/index.js"),

  // 出口
  output: {
    path: path.resolve(__dirname, "../dist"),
    filename: "[name].js"
  },

  module: {
    // Loader 规则
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: "babel-loader",
        // 排除 node_modules 文件夹
        exclude: [/node_modules/]
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      }
    ]
  },

  plugins: [
    // html-webpack-plugin
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html")
    }),

    // copy-webpack-plugin
    new CopyWebpackPlugin([{ from: path.resolve(__dirname, "../public") }])
  ]
};

  1. 配置开发环境 => webpack.dev.conf.js
// 1. 引入 base merge path
const path = require("path");
const baseConfig = require("./webpack.base.conf");
const merge = require("webpack-merge");

// 2. 暴露出去
module.exports = merge(baseConfig, {
  // mode
  mode: "development",

  // devServer
  devServer: {
    contentBase: path.resolve(__dirname, "../dist"),
    stats: "errors-only"
  }
});

  1. 配置生产环境 => webpack.prod.conf.js
// 1. 引入 base merge path
const path = require("path");
const baseConfig = require("./webpack.base.conf");
const merge = require("webpack-merge");

// 2. 暴露出去
module.exports = merge(baseConfig, {
  // mode
  mode: "production"
});

上一篇 下一篇

猜你喜欢

热点阅读