Webpack 配置 React 开发环境

11.18

介绍

Webpack 是前端流行的资源加载、打包的工程化工具。

Webpack 默认配置文件:webpack.config.js

测试环境: webpack 4, React 16

安装环境

进入项目目录

npm install webpack webpack-cli
npm install webpack-dev-server

npm install react react-dom

// babel 扩展
npm install babel-preset-stage-2

// react-hot-loader
npm install react-hot-loader

// plugins
npm install clean-webpack-plugin html-webpack-plugin

// redux
npm install redux react-redux

配置

package.json

通过npm run命令执行本地安装的 webpack 工具

"scripts": {
  "watch": "webpack --watch",
  "build": "webpack",
  "start": "webpack-dev-server --open"
}, 

webpack.config.js 配置

entry 目录下有入口文件 entry.jsx,其它组件等资源被其引用

output 通过entry.jsx,加载打包后输出到dist/bundle.js

resolve 可以 import 的文件后缀

module.rules 加载 js/jsx 时用 babel-loader来编译,这样就可以在这些文件中自由使用 JSX 和 ES6 了

其它配置

devtool: 开发模式下可以设置成 source-map https://webpack.js.org/configuration/devtool

详细配置

./webpack.config.js

var path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  entry: './index.jsx',
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx', 'css'],
  },
  module:{
    rules: [
      {
        test: /\.jsx?$/,
        loaders: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets: ['react', 'es2015', 'stage-2'],
          plugins: [
            ["import", { libraryName:'antd-mobile', style:'css' }],
          ]
        },
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      }
    ]
  },
  devServer: {
    contentBase: './dist',
    hot: true
  },
  plugins: [
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      template: './index-dev.html'
    }),
  ],
  mode: "development",
};

入口文件配置

index.jsx

import React from 'react'
import { render } from 'react-dom'
import App from './components/App'

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

if (module.hot) {
  module.hot.accept();
}

index-dev.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>React Example</title>
</head>
<body>
  <div id="root"></div>
</body>
</html>

开发

开发模式下动态编译:

webpack-dev-server --open

生产模式打包

webpack

使用:在 HTML 文件中引用 dist/bundle.js即可。

参考

Webpack 配置 React 开发环境

📖