2017-01-22 2 views
0

Я знаю, что есть много вопросов об этом, но я ищу решение для 14 часов в 2 дня.webpack hot reaload response

Я пытаюсь создать среду разработки для себя, но не повезло с горячим автоматическим обновлением.

I change webpack.config пункт ввода 'webpack/hot/dev-server'. когда я вхожу на сайт в браузере http://localhost:3000/ У меня есть сайт. в консоли он говорит: [HMR] Waiting for update signal from WDS..., но когда я что-то обновляю, страница не перезагружается. Ничего не произошло. Я вижу, что веб-пакет ловит изменения и обновляет пакет. Я вижу изменения, когда я перезагружаю страницу с помощью 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> 
+0

Просто уточнить: вы пытаетесь обновить файл HTML или JS? hot module не отслеживает изменения index.html по умолчанию – mrlew

+0

нет JS. У меня нет никакого дела с файлом html. страница не изменяется, когда я что-то меняю в src/index.js, которая является точкой входа. – Valour

ответ

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,