webpack hot reaload做出反应

时间:2017-01-22 20:53:55

标签: javascript webpack webpack-hmr

我知道有很多问题,但我在2天内寻找解决方案14小时。

我正在努力为自己建立一个开发环境,但热门自动更新没有运气。

我将webpack.config入口点更改为'webpack/hot/dev-server'。当我在浏览器http://localhost:3000/上进入网站时,我获得了该网站。在控制台中,它说:[HMR] Waiting for update signal from WDS...但是当我更新某些内容时,页面不会重新加载。什么都没发生。我可以看到webpack捕获更改并更新捆绑包。当我用F5重新加载页面时,我可以看到更改。

当我输入http://localhost/webpack-dev-server/时,只要我做出更改,它就会更新页面。但它会整页重新加载。

我知道也许这是一个简单的解决方案,但请相信我,我一直试图找到解决方案14个小时。我在拉我的头发。

我所有的配置都是这样的:

的package.json

{
  "name": "sample",
  "version": "0.1.0",
  "description": "sample",
  "private": true,
  "main": "index.js",
  "scripts": {
    "start": "cross-env NODE_ENV=development webpack-dev-server --config=./webpack.config.dev.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Gökhan Öztürk",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^6.7.0",
    "babel-core": "^6.22.1",
    "babel-eslint": "^7.1.1",
    "babel-loader": "^6.2.10",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-plugin-dev-expression": "^0.2.1",
    "babel-plugin-tcomb": "^0.3.24",
    "babel-plugin-webpack-loaders": "^0.8.0",
    "babel-polyfill": "^6.22.0",
    "babel-preset-env": "^1.1.8",
    "babel-preset-react": "^6.22.0",
    "babel-preset-react-app": "^2.0.1",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-preset-react-optimize": "^1.0.1",
    "babel-preset-stage-0": "^6.22.0",
    "cross-env": "^3.1.4",
    "css-loader": "^0.26.1",
    "eslint": "^3.14.0",
    "eslint-config-airbnb": "^14.0.0",
    "eslint-formatter-pretty": "^1.1.0",
    "eslint-import-resolver-webpack": "^0.8.1",
    "eslint-loader": "^1.6.1",
    "eslint-plugin-flowtype": "^2.30.0",
    "eslint-plugin-flowtype-errors": "^2.0.3",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^3.0.2",
    "eslint-plugin-promise": "^3.4.0",
    "eslint-plugin-react": "^6.9.0",
    "express": "^4.14.0",
    "file-loader": "^0.9.0",
    "flow-bin": "^0.38.0",
    "flow-typed": "^2.0.0",
    "html-webpack-plugin": "^2.26.0",
    "json-loader": "^0.5.4",
    "node-sass": "^4.3.0",
    "postcss-loader": "^1.2.2",
    "react-hot-loader": "^1.3.1",
    "redux-logger": "^2.7.4",
    "sass-loader": "^4.1.1",
    "style-loader": "^0.13.1",
    "tcomb": "^3.2.16",
    "url-loader": "^0.5.7",
    "webpack": "^1.14.0",
    "webpack-dev-middleware": "^1.9.0",
    "webpack-dev-server": "^1.16.2",
    "webpack-hot-middleware": "^2.15.0"
  },
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-redux": "^5.0.2",
    "react-router": "^3.0.2",
    "react-router-redux": "^4.0.7",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0"
  }
}

webpack.config.dev.js

const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
  return path.resolve(appDirectory, relativePath);
}

module.exports = {
  debug: true,

  devtool: 'inline-sourcemap',

  entry: [
    'webpack-hot-middleware/client?http://localhost:3000/',
    'webpack/hot/only-dev-server',
    'babel-polyfill',
    './src/index'
  ],

  output: {
    path: resolveApp('build'),
    pathinfo: true,
    filename: 'static/js/bundle.js',
    publicPath: 'http://localhost:3000/'
  },

  resolve: {
    extensions: ['.js', '.json', '.jsx', '']
  },

  module: {
    // First, run the linter.
    // It's important to do this before Babel processes the JS.
    preLoaders: [
      {
        test: /\.(js|jsx)$/,
        loader: 'eslint',
        include: resolveApp('src'),
      }
    ],
    loaders: [
      // Diğer loaderlar tarafından işlem görmeyecek her dosya buradan yönlendirilecek.
      {
        exclude: [
          /\.html$/,
          /\.(js|jsx)$/,
          /\.css$/,
          /\.(scss|sass)$/,
          /\.json$/,
          /\.svg$/
        ],
        loader: 'url',
        query: {
          limit: 10000,
          name: 'static/media/[name].[hash:8].[ext]'
        }
      },

      {
        test: /\.css$/,
        loader: 'style!css?importLoaders=1!postcss'
      },
      {
        test: /\.(scss|sass)$/,
        loader: 'style!css?importLoaders=1!postcss!sass'
      },
      // JSON is not enabled by default in Webpack but both Node and Browserify
      // allow it implicitly so we also enable it.
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.(js|jsx)$/,
        loader: 'react-hot!babel',
        // loader: 'babel?cacheDirectory=true',
        include: resolveApp('src'),
        exclude: /node_modules/
      }
    ]
  },

  // We use PostCSS for autoprefixing only.
  postcss: function postCssAutoprefixer() {
    return [
      autoprefixer({
        browsers: [
          '>1%',
          'last 4 versions',
          'Firefox ESR',
          'not ie < 9', // React doesn't support IE8 anyway
        ]
      }),
    ];
  },

  plugins: [
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: resolveApp('public/index.html'),
    }),

    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),

    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ],

  devServer: {
    hot: true,
    contentBase: './src',
    port: 3000
  },

  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  }
};

.babelrc

{
  "presets": [
    "react",
    "es2015"
  ],
  "plugins": ["add-module-exports"],
  "env": {
    "production": {
      "presets": ["react-optimize"],
      "plugins": ["babel-plugin-dev-expression"]
    },
    "development": {
      "plugins": [
        "transform-class-properties",
        "transform-es2015-classes",
        "tcomb"
      ],
      "presets": ["react-hmre"]
    }
  }
}

公开/ index.html中

<!doctype html>
<html lang="tr">
  <head>
    <title>site</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

看看一个有效的例子:

main.js

const express = require('express')
const debug = require('debug')('app:server')
const path = require('path')
const webpack = require('webpack')
const webpackConfig = require('../config/webpack.config')
const project = require('../config/project.config')
const compress = require('compression')

const app = express()

// Apply gzip compression
app.use(compress())

// ------------------------------------
// Apply Webpack HMR Middleware
// ------------------------------------
if (project.env === 'development') {
  const compiler = webpack(webpackConfig)

  debug('Enabling webpack dev and HMR middleware')
  app.use(require('webpack-dev-middleware')(compiler, {
    publicPath  : webpackConfig.output.publicPath,
    contentBase : project.paths.client(),
    hot         : true,
    quiet       : project.compiler_quiet,
    noInfo      : project.compiler_quiet,
    lazy        : false,
    stats       : project.compiler_stats
  }))
  app.use(require('webpack-hot-middleware')(compiler, {
    path: '/__webpack_hmr'
  }))

  // Serve static assets from ~/public since Webpack is unaware of
  // these files. This middleware doesn't need to be enabled outside
  // of development since this directory will be copied into ~/dist
  // when the application is compiled.
  app.use(express.static(project.paths.public()))

  // This rewrites all routes requests to the root /index.html file
  // (ignoring file requests). If you want to implement universal
  // rendering, you'll want to remove this middleware.
  app.use('*', function (req, res, next) {
    const filename = path.join(compiler.outputPath, 'index.html')
    compiler.outputFileSystem.readFile(filename, (err, result) => {
      if (err) {
        return next(err)
      }
      res.set('content-type', 'text/html')
      res.send(result)
      res.end()
    })
  })
} else {
  debug(
    'Server is being run outside of live development mode, meaning it will ' +
    'only serve the compiled application bundle in ~/dist. Generally you ' +
    'do not need an application server for this and can instead use a web ' +
    'server such as nginx to serve your static files. See the "deployment" ' +
    'section in the README for more information on deployment strategies.'
  )

  // Serving ~/dist by default. Ideally these files should be served by
  // the web server and not the app server, but this helps to demo the
  // server in production.
  app.use(express.static(project.paths.dist()))
}

module.exports = app

DEV-server.js

const project = require('../config/project.config')
const server = require('../server/main')
const debug = require('debug')('app:bin:dev-server')

server.listen(project.server_port)
debug(`Server is now running at http://localhost:${project.server_port}.`)

project.config.js

  // ----------------------------------
  // Server Configuration
  // ----------------------------------
  server_host : ip.address(),  
  server_port : process.env.PORT || 1024,