webpack-hot-middleware
webpack-hot-middleware copied to clipboard
How to update CSS changes when using ExtractTextPlugin?
I'm using Webpack 2 and ExtractTextPlugin however, I can't set an entry point for the styles.css, and they're totally ignored by the whm.
Any ideas on how to workaround that? For the webpack-dev-server I have a custom script in the setup for the callbacks that checks changes in the stats and when sending the data to the client, it injects a custom call that triggers the CSS replace in the frontend by the new styles.css file. I I couldn't do that so far using whm because it doesn't send the hot-updates.js file when it's not in the current entry point.
Second!
Same issue here... I include a LESS file within my module which is supposed to be included as a separate CSS file thanks to ExtractTextWebpackPlugin. Compilation is well done as I can see it within my terminal as well as in Chrome console but no change is triggered in the browser when I update my file.
Here is the server code :
(function () {
'use strict';
const Express = require('express');
const Http = require('http');
const Path = require('path');
const Webpack = require('webpack');
const WebpackDevMiddleware = require('webpack-dev-middleware');
/**
* 1 : First of all, we have to create our webpack compiler using our dev configuration
*/
const config = require('./webpack.dev.config');
const compiler = Webpack(config);
/**
* 2 : Then, we now create our basic Express application and attach a Morgan logger to it
*/
let app = Express();
app.use(require('morgan')('short'));
/**
* 3 : Let's now attach the webpack-dev-middleware with the compiler to our application
*/
app.use(WebpackDevMiddleware(compiler, {
hot: true,
historyApiFallback: false,
quiet: false,
noInfo: false,
contentBase: Path.join(__dirname, '../../public/'),
publicPath: config.output.publicPath,
stats: {
colors: true,
chunks: false
},
watchOptions: {
aggregateTimeout: 300,
poll: 50
},
headers: { "Access-Control-Allow-Origin": "*" }
}))
/**
* 4 : Then, we attach the webpack-hot-middleware to our application and to the compiler
*/
let WebpackHotMiddleware = require('webpack-hot-middleware')(compiler, {
path: '/__assets_store'
});
app.use(WebpackHotMiddleware);
/**
* 5 : Finally, we can start our server and serve our assets using hot reloading
*/
const Server = Http.createServer(app);
Server.listen(8081, function(err) {
if (err) {
console.log(err);
return;
}
console.log("Listening on http://localhost:8081 ...");
});
}())
Then, the webpack.dev.config.js
(function () {
'use strict';
const path = require('path');
const Webpack = require('webpack');
let config = require('./webpack.config');
config.output.publicPath = 'http://localhost:8081' + config.output.publicPath;
for (var entrypoint in config.entry) {
if (config.entry.hasOwnProperty(entrypoint)) {
let HMRConfig = 'webpack-hot-middleware/client?reload=true&path=http://localhost:8081/__assets_store';
if (Array.isArray(config.entry[entrypoint])) {
config.entry[entrypoint].push(HMRConfig)
} else {
config.entry[entrypoint] = [
config.entry[entrypoint],
HMRConfig
];
}
}
}
config.plugins.push(
new Webpack.optimize.OccurenceOrderPlugin(),
new Webpack.HotModuleReplacementPlugin(),
new Webpack.NoErrorsPlugin()
);
module.exports = config;
}())
And finally, the webpack.config.js ("inherited" bu the dev config and used to build with the "webpack" command) :
(function () {
'use strict';
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
'billy-joe-studio.theme': path.join(__dirname, '../assets/modules/Theme.js')
},
output: {
path: path.join(__dirname, '../../public/dist/'),
publicPath: '/dist/',
filename: '[name].js'
},
module: {
preLoaders: [],
loaders: [
{
test: /.less$/,
loader: ExtractTextPlugin.extract('style', 'css!less'),
include: [
path.resolve(__dirname, '../assets/less')
]
}
]
},
plugins: [
new ExtractTextPlugin('css/[name].css')
]
}
}())
Any advice will be greatly appreciated :)
@gartz @arnaud-xp You can use browser-sync for sync your changes. Of course all changes must be saved to disk and write-file-webpack-plugin can make it. See my dev server config:
/**
* BrowserSync and webpack
*
* See also https://github.com/erikras/react-redux-universal-hot-example/pull/693/files
* for use express
* */
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const browserSync = require('browser-sync').create();
const historyApiFallback = require('connect-history-api-fallback');
const
WEBPACK_CONFIG = require(process.env.WEBPACK_CONFIG ? process.env.WEBPACK_CONFIG : './webpack.config'),
PORT = process.env.VIRTUAL_PORT ? process.env.VIRTUAL_PORT : '3000',
HOST = process.env.VIRTUAL_HOST ? '0.0.0.0' : 'localhost';
const compiler = webpack(WEBPACK_CONFIG);
browserSync.init({
ui: false,
open: false,
server: {
baseDir: 'public',
middleware: [
historyApiFallback(), // see https://github.com/BrowserSync/browser-sync/issues/204
webpackDevMiddleware(compiler, {
publicPath: WEBPACK_CONFIG.output.publicPath,
stats: { colors: true },
watchOptions: {
aggregateTimeout: 300,
poll: true
}
}),
webpackHotMiddleware(compiler, {
log: console.log,
path: '/__webpack_hmr',
heartbeat: 10 * 1000
})
]
},
port: PORT,
host: HOST,
// no need to watch '*.js' here, webpack will take care of it for us,
// including full page reloads if HMR won't work
files: [
'public/dist/*.css',
'public/*.html'
]
});
...and webpack config example for React and LESS
let
path = require('path'),
fs = require('fs'),
webpack = require('webpack'),
babelrc = JSON.parse(fs.readFileSync('./.babelrc')), // require JSON without extension
ExtractTextPlugin = require('extract-text-webpack-plugin'),
WriteFilePlugin = require('write-file-webpack-plugin');
const
PUBLIC_PATH = process.env.PUBLIC_PATH,
NODE_ENV = process.env.NODE_ENV;
let
entrypoints = [],
plugins = [];
if (NODE_ENV == 'development') {
entrypoints.push(
'webpack-hot-middleware/client',
'react-hot-loader/patch'
);
babelrc.plugins.push('react-hot-loader/babel');
plugins.push(
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new WriteFilePlugin({
test: /\.css$/
})
);
}
module.exports = {
context: path.join(__dirname, 'client'),
entry: {
main: entrypoints.concat([
'./index'
])
},
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: path.join(__dirname, 'public/dist'),
publicPath: PUBLIC_PATH ? PUBLIC_PATH : 'dist/',
filename: '[name].js',
chunkFilename: '[id].js'
},
devtool: NODE_ENV == 'development' ? 'inline-source-map' : null,
module: {
loaders: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel',
query: babelrc
},
{
test: /\.(less)$/,
loader: ExtractTextPlugin.extract('style', 'css?sourceMap!less?sourceMap', {publicPath: ''})
}
]
},
plugins: plugins.concat([
// Some plugins
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('[name].css')
])
};
It's work perfect for my.
Although it's not documented, you can send custom messages down the middleware's connection:
See https://github.com/glenjamin/webpack-hot-middleware/issues/23 for more info.
If anyone fancies sending a PR for docs on this that'd be great.
@gartz tbh using ExtractTextPlugin in development is generally not recommended -- there's really no need and without it you get HMR for free -- https://github.com/webpack/extract-text-webpack-plugin/issues/30#issuecomment-107242576
You can emit custom events and receive them on client side to reload css files.
// code in your dev-server.js
compiler.plugin('compilation', function (compilation) {
compilation.plugin('extract-text-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'css-file-changed' })
cb()
})
})
// code in your dev-client.js
var hotClient = require('webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true')
hotClient.subscribe(function (event) {
if (event.action === 'reload') {
console.log('reload event')
window.location.reload()
} else if (event.action === 'css-file-changed') {
console.log('css-file-changed event')
window.location.reload()
}
})
@jerrydotlam I'm assuming you left client side implementation to us. Here is a simple one:
hotClient.subscribe(function (event) {
if (event.action === 'reload') {
console.log('reload event')
window.location.reload()
} else if (event.action === 'css-file-changed') {
console.log('css-file-changed event')
Array.from(document.head.querySelectorAll('link')).forEach(link =>
const href = link.href
document.head.removeChild(link)
const newlink = document.createElement('link');
newlink.href = href;
document.head.appendChild(newlink)
);
}
})
@jerrydotlam is that "extract-text-plugin-after-emit" correct? I can't find that anywhere and it doesn't fire after the text extraction…
@mohsen1 you are missing {} in your foreach, and the reload thing is already done by the hot-middleware client, but other than than, great!
Here's what I ended up doing:
const extractStyles = (loaders) => {
if ( process.env.NODE_ENV === 'production') {
return ExtractTextPlugin.extract({
fallback: 'style-loader',
use: loaders,
});
}
return ['style-loader', ...loaders];
};
rules: [{
test: /\.scss$/,
use: extractStyles(['css-loader', 'sass-loader']),
}, {
test: /\.css$/,
use: extractStyles(['css-loader']),
}];
If your node version doesn't support array spread, you could use array concat.
Closing due to inactivity. Please test with latest version and feel free to reopen if still regressions. Thanks!