Webpack没有自动编译对React文件中代码的更改

Webpack not compiling changes to code in React file automatically

本文关键字:文件 代码 React 编译 Webpack      更新时间:2023-09-26

我最近开始尝试将React与Webpack一起使用,以便在发生更改时自动编译更改。然而,尽管我在谷歌上搜索得很满意,但我似乎找不到为什么它不起作用。

app.js

import React from 'react'
import ReactDOM from 'react-dom'
import {Router, Route, Link} from 'react-router'
import ProductList from './products'
class Main extends React.Component {
    constructor(props){
        let products = [];
        super(props);
        this.state = {
            name: "Harry"
        };
    }
    render(){
        return(
            <Storefront name={this.state.name} />
        );
    }
}
var a = 10;
let Storefront = (props) =>
<div className="container">
    <h4>Welcome to the React Store Front, {props.name}!</h4>
    <Link to="/products">View Products</Link>
</div>;
ReactDOM.render(
    <Router>
        <Route path="/" component={Main}/>
        <Route path="/products" component={ProductList}/>
    </Router>,
    document.getElementById("app")
);

package.json

{
  "name": "static",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "history": "^1.13.1",
    "react-router": "^1.0.2"
  },
  "devDependencies": {
    "babel-core": "^6.3.17",
    "babel-loader": "^6.2.0",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0"
  },
  "scripts": {
    "dev": "webpack-dev-server --inline --hot --progress --colors --port 8090",
    "test": "echo '"Error: no test specified'" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "private": true
}

webpack.config.js

module.exports = {
    context: __dirname,
    entry: ['webpack/hot/dev-server', './app.js'],
    output: {
        filename: "app.js",
        path: __dirname + "/dist"
    },
    module: {
        loaders: [
            {
                test: /'.js$/,
                exclude: /node_modules/,
                loaders: ["babel-loader?presets[]=react,presets[]=es2015"]
            },
            {
                test: /'.jsx$/,
                loaders: ['babel-loader?presets[]=react,presets[]=es2015']
            }
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    watch: true
};

您必须使用webpack-hot-middleware NPM链接是NPM

如果你想举例,那么你可以使用react路由器举例react路由器

我使用了和我的webpack.config文件

/* eslint-disable no-var */
var path = require('path');
var webpack = require('webpack');
module.exports = {
  entry: [
    'webpack-hot-middleware/client',
    './scripts/index'
  ],
  devtool: 'eval-source-map',
  output: {
    path: __dirname,
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [{
      test: /'.js$/,
      loaders: ['babel'],
      include: path.join(__dirname, 'scripts')
    }]
  }
};