Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to hot reload a CSS file in Webpack using Webpack Dev Middleware

I have a project written in TypeScript that I can take advantage of Webpack Hot Reload, using both webpack-hot-middleware and webpack-dev-middleware libraries in my Node.js server.

Also, I already have all the build steps configured for my Stylus code (incremental builds with Gulp), that generates one single CSS file in my public directory.

So, now I would like to take advantage of Webpack's hot reloading for CSS as well, since I already have that for my TypeScript stuff, but I don't want it to build my CSS files, since I already have something great for that. Ideally, I only want to have Webpack hot reloading my single CSS file everytime it changes. What is the simplest and best way to achieve that?

My current configuration file looks like this:

const webpack = require('webpack');

module.exports = {
  entry: [
    'webpack-hot-middleware/client',
    './src/client/index.tsx'
  ],
  output: {
    path: '/public/js/',
    filename: 'bundle.js',
    publicPath: '/js/'
  },
  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
  },
  module: {
    loaders: [
      {
        test: /\.tsx?$/,
        loader: 'ts-loader'
      }
    ]
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ];
};

And then, I use Webpack Hot Middleware and Webpack Dev Middleware like this:

const webpackConfig = require('../webpack.config');
const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
like image 417
Buzinas Avatar asked May 13 '16 07:05

Buzinas


1 Answers

I don't think you need to do anything special for HMR to deal with css files apart from the configuration you already have. But Webpack needs to see your css as a dependency of your application. You could require (or import) one or more css files in your javascript, and by doing so it becomes part of the application dependency tree.

In a standard setup you would match .css files to use the css-loader and have it transpiled before emitting it to the output, but since you don't want Webpack to touch your css you could use the file-loader instead. Webpack will still pick up the file as a dependency but simply copy it to the output directory without touching its contents.

Put something like: require("file!./styles.css"); in your application main file. This will instruct it to use the file loader on the css file. You will need to install file-loader with NPM since it's not part of Webpack.

like image 72
Thijs Koerselman Avatar answered Oct 20 '22 00:10

Thijs Koerselman