index.html使用webpack开发服务器未重新加载

index.html using webpack-dev-server not reload

本文关键字:新加载 加载 使用 html webpack 开发 服务器 index      更新时间:2023-09-26

当我在webpack-dev-server运行时更改app.jsmain.css时,捆绑包会更新。但是当我改变index.html时,内容不被刷新;如果我在HTML中添加一行,webpack-dev-server不会刷新页面上的任何内容。这是我的webpack.config.jspackage.json文件。我希望你能帮助我。

webpack.config.js

var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server'); 
var CleanWebpackPlugin = require('clean-webpack-plugin'); 
var chalk = require('chalk');  
var env = process.env.WEBPACK_ENV;
var host = 'localhost';
var port = '8080';
var config = {
  devtool: 'source-map',
  entry: [
    'webpack/hot/dev-server',
    'webpack-dev-server/client?http://' + host + ':' + port +'/',
    './src/app.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js'
  },
  module : {
    loaders: [
      { test: /'.css$/, loader: 'style-loader!css-loader' },
      { test: /'.html$/,loader: 'file?name=[name].[ext]' }
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new CleanWebpackPlugin(['dist'], {
      root: __dirname,
      verbose: true,
      dry: false
    })
  ]
};
if (env === 'dev') {
  new WebpackDevServer(webpack(config), {
    contentBase: './dist/',
    stats: {colors: true},
    hot: true,
    debug: true
  }).listen(port, host, function (err, result) {
    if (err) {
      console.log(err);
    }
  });
  console.log('-------------------------');
  console.log(chalk.bold.white('Local web server runs at ') + chalk.green('http://' + host + ':' + port));
  console.log('-------------------------'n'n');
}
module.exports = config;

package.json:

{
  "name": "webpack-skeleton",
  "version": "1.0.0",
  "description": "webpack skeleton",
  "main": "bundle.js",
  "scripts": {
    "test": "echo '"Error: no test specified'" && exit 1",
    "start": "WEBPACK_ENV=dev ./node_modules/.bin/webpack --watch --inline"
  },
  "author": "Jose Roa",
  "license": "ISC",
  "devDependencies": {
    "chalk": "^1.1.3",
    "clean-webpack-plugin": "^0.1.9",
    "css-loader": "^0.23.1",
    "file-loader": "^0.8.5",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.0",
    "webpack-dev-server": "^1.14.1"
  }
}

我的目录结构:

css  
  main.css
dist
  bundle.js
  bundle.js.map
  index.html
node_modules
src
  app.js
  sum.js
package.json
index.html
node_modules
webpack.config.js

dist目录中的每个文件都是由webpack生成的。

添加HtmlWebpackPlugin链接:https://www.npmjs.com/package/html-webpack-plugin添加

// webpack.config.js
const HtmlWebpackPlugin =  require('html-webpack-plugin');
module.exports = {
    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html'
        })
    ]
};

这可能是由于您的IDE——请参阅webpack开发服务器

与支持"安全写作"的编辑/IDE合作。。。这种行为会导致文件观察程序丢失跟踪,因为原始文件已被删除。为了防止这个问题,您必须禁用编辑器中的"安全写入"功能。

您可以在开发应用程序时尝试这种自动重新加载的解决方法。添加到您的入口点('./src/app.js'):

require('../index.html'); //workround to reload page on index.html changes