当我设置Babel es2015预设时,为什么热模块更换在webpack dev服务器上停止工作?

时间:2017-02-25 11:12:09

标签: reactjs webpack webpack-dev-server hot-module-replacement

我有一个小应用程序在webpack dev服务器上运行(在开发环境中)。

热模块更换运行良好,我可以在编辑js文件时即时查看我的更改。

但是,只要我在babel loader配置中添加es2015预设,它就会停止工作!

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');

process.env.BABEL_ENV = 'development';

module.exports = {
  entry: {
    app: ['react-hot-loader/patch', path.join(__dirname, 'src')]
  },
  output: {
    path: path.join(__dirname, 'build'),
    filename: '[name].js',
  },
  module: {
   rules: [
     {
       test: /\.js$/,
       include: path.join(__dirname, 'src'),
       use: {
         loader: 'babel-loader',
         options: {
           cacheDirectory: true,
           presets: ['react'],
         },
       },
     }
   ]
  },
  devServer: {
    historyApiFallback: true,
    quiet: true,
    hotOnly: true,
    contentBase: './build',
    host: 'my-host.local',
    port: 8091,
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000,
    },
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Webpack demo',
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new FriendlyErrorsWebpackPlugin(),
    new webpack.WatchIgnorePlugin([
      path.join(__dirname, 'node_modules')
    ]),
  ],
};

src / index.js文件:

import React from 'react';
import ReactDOM from 'react-dom';
import Component from './Component';
import { AppContainer } from 'react-hot-loader';

const app = document.createElement('div');
document.body.appendChild(app);

const render = App => {
  ReactDOM.render(
    <AppContainer><App /></AppContainer>,
    app
  );
};

render(Component);

if (module.hot) {
  module.hot.accept('./Component', () => render(Component));
}

Component.js

import React from 'react';

export default class Title extends React.Component {
  render() {
    return (
      <div>Ass</div>
    );
  }
}

.babelrc

{
  "presets": [
    [
      "react",
      "es2015",
      {
        "modules": false
      }
    ]
  ],
  "env": {
    "development": {
      "plugins": [
        "react-hot-loader/babel"
      ]
    }
  }
}

我一接替

presets: ['react'],

通过

presets: ['es2015', 'react'],

热模块更换功能停止工作..有人在这里有线索吗?

(也不要在我的代码中指出不良做法或可避免的并发症)

1 个答案:

答案 0 :(得分:1)

您需要以下.babelrc(我不知道为什么)。

.babelrc

{
  "presets": [
    ["es2015", {"modules": false}],
    "stage-2",
    "react"
  ],
}

其中stage-2是npm包babel-preset-stage-2