Webpack不会自动编译React文件中的代码更改

时间:2015-12-22 12:59:26

标签: javascript reactjs webpack babeljs

我最近开始尝试使用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
};

1 个答案:

答案 0 :(得分:0)

您必须使用webpack-hot-middleware NPM链接为http://www.roblox.com

如果您想要示例,那么您可以使用react-router示例NPM

我使用过我的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')
    }]
  }
};