Good morning,
Rise and shine, the sun is already high in the sky and webpack is ruining my day!
I'm using webpack-dev-server (through a script in packages.json):
"scripts": {
"dev-server": "webpack-dev-server",
}
That I run with yarn run dev-server
What I want is the code to recompile and the browser to refresh whenever I save a file. I can live with the fact that it doesn't work with SCSS files, but recompiling "manually" on each change in my components is just physically painful. I tried a lot of solution found online (non-exhaustive list coming) before asking here, but the result is always the same:
ℹ 「wdm」: Compiled successfully
And nothing happens when I modify a file (JS or SCSS).
This is a simple React app, with SCSS for styling.
Here is my webpack config:
const path = require('path');
const MiniCSSExtractPlugin = require('mini-css-extract-plugin');
const mode = process.env.NODE_ENV || 'development';
module.exports = env => {
return {
entry: ['babel-polyfill', './src/app.js'],
output: {
path: path.join(__dirname, 'public', 'dist'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}, {
test: /\.s?css$/,
loader: [
mode === 'development' ? 'style-loader' : MiniCSSExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
}
]
},
plugins: [
new MiniCSSExtractPlugin({ filename: 'styles.css' })
],
devtool: env === 'production' ? 'source-map' : 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(__dirname, 'public'),
publicPath: '/dist/'
}
};
};
Here a list of things I tried:
Add --output-public-path=/dist/ to the script
Use the following content to the devServer config in webpack.config.js:
host: '0.0.0.0',
contentBase: path.join(__dirname, 'public'),
publicPath: '/dist/',
historyApiFallback: true,
compress: true,
port: 8080,
watchContentBase: true,
inline: true,
hot: true
Use HtmlWebpackConfig with the following config:
new HtmlWebpackPlugin({
title: 'Prognostic',
filename: './public/dist/index.html',
template: './public/index.html'
})
Remove / add webpack and webpack-dev-server
Use a global webpack-dev-server instead of the project one (npm i -g webpack-dev-server)
Certainly more things but I don't remember... Whoops
For information, here are the version I use:
Babel-loader#7
react#^16.8.6,
webpack-dev-server#^3.9.0
webpack#^4.41.2
So, I'd like two things to happen:
Automatic recompile when JS file changed
Automatic recompile when SCSS file changed (if possible)
If you can help me do that, I'll nominate you my Santa Dev of the year (yes, you can add that to your CV)
Thank you!
PS: great laugh when Grammarly told me that my text sounds "friendly"
Webpack dev server adds a watcher on your files to trigger the compilation when they have been modified.
Sometimes though, depending on the text editor you are using, this won't trigger at all.
I had the same problem, using sublimetext : when I saved my code the webpack dev server wouldn't rebuild.
So instead of using the default triggering mechanism, I'm using another option of webpack :
devServer: {
hot: true,
watchOptions: {
aggregateTimeout: 300,
poll: true
},
}
Every 300ms the server will check if files have changed and if so, rebuild.
I hope I am your Santa Dev of the year :]
I don't think you can do this by webpack you need to use library like react-hot-loader
Related
This has got to be one of the strangest issues with webpack i have ever come across...
Check out this bundle breakdown:
react 116.01KB - fair enough
react-dom 533.24KB - seriously WTF
I thought it may be a corruption in my dependencies but nuking node_modules and reinstalling doesn't have any effect. I guess it's something to do with the way webpack is bundling it but i'm lost for ideas. The way i'm handing .js imports is pretty stock standard.
// webpack.config.js
const path = require('path');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const Dashboard = require('webpack-dashboard');
const DashboardPlugin = require('webpack-dashboard/plugin');
const dashboard = new Dashboard();
module.exports = {
context: path.join(__dirname, 'src'),
entry: {
bundle: './index.js',
},
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'build'),
},
module: {
rules: [
{
test: /\.html$/,
use: 'file-loader?name=[name].[ext]',
},
{
test: /.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
'postcss-loader',
],
}),
},
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
],
},
plugins: [
// new BundleAnalyzerPlugin(),
new ExtractTextPlugin('styles.css'),
new DashboardPlugin(dashboard.setData),
],
devServer: {
quiet: true,
},
};
// .babelrc
{
"presets": [
"react",
"es2015"
],
"plugins": ["transform-object-rest-spread"]
}
http://elijahmanor.com/react-file-size/
In v15.4.0 the file size of react-dom grew from 1.17kB to 619.05kB. Which means my webpack setup isn't doing anything wrong bundling files. The reason why this module grew so large is because code was transferred from the react module.
I had to change my webpack.config.js, from
devtool: 'inline-source-map'
to
devtool: 'source-map'
Now it generates a much smaller .js + a separate .js.map file, for each of the chunks.
Notice the JS size is even less than react-dom.production.min.js in node_modules:
If you look into the corresponding folders under the node_modules folder, and note the file sizes, you'll see that there's nothing to be surprised about:
That is, the size of the bundle grows noticeably because the size of react-dom.js is large.
Add this following commands at plugins to minify your imports:
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.DefinePlugin(GLOBALS),
new webpack.optimize.UglifyJsPlugin(),
You should create a file or option to production bundle to use this plugins
I am using webpack for bundling. I am using reactjs and django. I want the static files used by Django and reactjs be separate. I could minified image but the minified images are saved to the folder where the output file is bundled. I want all the minified images to be saved inside frontend -> assets folder. How can i do it so?
The project structure looks like following
app - its a directory where static files are kept for Django. Webpack bundles the react files to app.js and is placed over here because Django template need it to render in its template as <script src='app/bundle/js/app.js'></script>.
frontend - It's a directory where all the react files reside. I want the images to be inside this directory(assets/images/). Images that will be used in reactjs.
How can i do it so?
my webpack right now is configured this way
const path = require("path");
if(!process.env.NODE_ENV) {
process.env.NODE_ENV = 'development';
}
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: path.join("../app/static/build/", "js"),
filename: "app.js",
publicPath: "../app/static/build/"
},
devtoo: 'source-map',
debug: true,
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=images/[name].[ext]"},
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
You can specify custom output and public paths by using the outputPath and publicPath query name parameters:
loader: "file-loader?name=[name].[ext]&publicPath=assets/foo/&outputPath=app/images/"
But this feature isn't published to NPM yet. So unfortunatly you'll need to wait while it be published or clone and use this loader from github repo
I have a React Redux app and am trying to put it on a static file server (so the user should just be able to go to http://myurl.com/thePath/index.html and the app should load). Right now I'm using webpack to bundle my assets. Here is my webpack build file:
webpack.config.prod.js:
import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import WebpackMd5Hash from 'webpack-md5-hash';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import autoprefixer from 'autoprefixer';
import path from 'path';
const GLOBALS = {
'process.env.NODE_ENV': JSON.stringify('production'),
__DEV__: false
};
export default {
resolve: {
extensions: ['', '.js', '.jsx']
},
debug: true,
devtool: 'source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
noInfo: true, // set to false to see a list of every file being bundled.
entry: path.resolve(__dirname, 'src/index'),
target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/thePath/',
filename: '[name].[chunkhash].js'
},
plugins: [
// Hash the files using MD5 so that their names change when the content changes.
new WebpackMd5Hash(),
// Optimize the order that items are bundled. This assures the hash is deterministic.
new webpack.optimize.OccurenceOrderPlugin(),
// Tells React to build in prod mode. https://facebook.github.io/react/downloads.html
new webpack.DefinePlugin(GLOBALS),
// Generate an external css file with a hash in the filename
new ExtractTextPlugin('[name].[contenthash].css'),
// Generate HTML file that contains references to generated bundles. See here for how this works: https://github.com/ampedandwired/html-webpack-plugin#basic-usage
new HtmlWebpackPlugin({
template: 'src/index.ejs',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
},
inject: true,
// Note that you can add custom options here if you need to handle other custom logic in index.html
// To track JavaScript errors via TrackJS, sign up for a free trial at TrackJS.com and enter your token below.
trackJSToken: ''
}),
// Eliminate duplicate packages when generating bundle
new webpack.optimize.DedupePlugin(),
// Minify JS
new webpack.optimize.UglifyJsPlugin()
],
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel'},
{test: /\.(eot|woff|woff2|svg|ttf)([\?]?.*)$/, loader: "file-loader" },
{test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]'},
{test: /\.ico$/, loader: 'file?name=[name].[ext]'},
{test: /(\.css|\.scss)$/, loader: ExtractTextPlugin.extract('css?sourceMap!postcss!sass?sourceMap')}
]
},
postcss: ()=> [autoprefixer]
};
So webpack bundles everything fine, but when I put the files it outputs into /thePath/ and then go to http://myurl.com/thePath/index.html, I get an empty white screen. It loads the CSS and JS resources but nothing shows up. It loads fine when it is served through webpack's dev server. How can I resolve this?
Answer can be found here: Why is React Webpack production build showing Blank page?
Long story short, when using browserHistory with react-router, your server must be configured to support it. If your server is not configured to support it, you must use hashHistory.
I've looked around, but can't get any of the answers I've seen on stackoverflow to work.
I cannot use the command line for webpack or the webpack dev-server; I am restricted to using the Node API.
Below is how I am using webpack.
webpack.config.js
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:3000',
// i've also tried webpack/hot/dev-server here
'webpack/hot/only-dev-server',
path.join(__dirname, 'src', 'js', 'app.jsx')
],
output: {
path: path.join(__dirname, 'dist', 'js'),
filename: 'script.js',
publicPath: '/dist/'
},
module: {
loaders: [{
test: /\.(js|jsx)$/,
loaders: ['react-hot', 'babel']
}]
},
plugins: []
};
contained in a gulp task "start"
gulp.task('start', function (callback) {
var config = Object.create(require('webpack.config.js'));
config.plugins.push(new webpack.HotModuleReplacementPlugin());
var devServer = new webpackDevServer(webpack(config), {
stats: { colors: true },
contentBase: path.resolve(__dirname, 'dist'),
progress: true,
inline: true,
hot: true
});
});
What I expect
When I run gulp start, I expect the webpack dev server to spin up, allowing me to hit localhost:3000/. This should load an index.html from my project's /dist/ folder. So far so good. I expect that when I make a change to a file (e.g., app.jsx), that the change would be present.
What is actually happening
I am getting the error "[HMR] Hot Module Replacement is disabled", with no further explanation.
Any help would be appreciated. I have been trying to get hot reloading working for a full day.
in your webpack.config.js on the plugins section try this,
plugins: [new webpack.HotModuleReplacementPlugin()]
I know you are pushing the plugin in your gulp task but you have to use --hot --inline on cli or on your npm script
Try to run webpack as
webpack-dev-server --hot --inline in packge.json,
somehow official docs is wrong now.
I'm trying to use webpack-dev-server to compile files and start up a dev web server.
In my package.json I have the script property set to:
"scripts": {
"dev": "webpack-dev-server --hot --inline",
}
So the --hot and --inline should enable the webserver and the hot reloading (as I understand it).
In my webpack.config.js file I set the entry, output, and devServer settings as well as add a loader to look for changes in .vue files:
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/public',
publicPath: '/public',
filename: 'bundle.js'
},
devtool: 'source-map',
devServer:{
contentBase: __dirname + '/public'
},
module:{
loaders:[
{ test: /\.vue$/, loader: 'vue'}
]
}
};
So with this setup, I run npm run dev. The webpack-dev-server starts up, the module loader test works (i.e. when I save any .vue file it causes webpack to recompile), but:
The browser never refreshes
The compiled javascript that gets stored in memory is never made available to the browser
On that second bullet, I can see this because in the browser window the vue placeholders are never replaced and if I open up the javascript console the Vue instance is never created or made available globally.
What am I missing?
Two things were causing my problems here:
module.exports = {
entry: './src/index.js',
output: {
// For some reason, the `__dirname` was not evaluating and `/public` was
// trying to write files to a `public` folder at the root of my HD.
path: __dirname + '/public',
// Public path refers to the location from the _browser's_ perspective, so
// `/public' would be referring to `mydomain.com/public/` instead of just
// `mydomain.com`.
publicPath: '/public',
filename: 'bundle.js'
},
devtool: 'source-map',
devServer:{
// `contentBase` specifies what folder to server relative to the
// current directory. This technically isn't false since it's an absolute
// path, but the use of `__dirname` isn't necessary.
contentBase: __dirname + '/public'
},
module:{
loaders:[
{ test: /\.vue$/, loader: 'vue'}
]
}
};
Here's the fixed webpack.config.js:
var path = require('path');
module.exports = {
entry: [
'./src/PlaceMapper/index.js'
],
output:{
filename: 'bundle.js',
path: path.resolve(__dirname, 'public/')
},
devtool: 'source-map',
devServer:{
contentBase: 'public'
},
module:{
loaders:[
{ test: /\.vue$/, loader: 'vue'}
]
}
};
After a long search I found the solution for my problem, in my case output path wasn't configured correctly.
This configuration solved my problem:
const path = require('path');
module.exports = {
"entry": ['./app/index.js'],
"output": {
path: path.join(__dirname, 'build'),
publicPath: "/build/",
"filename": "bundle.js"
}....
the right solution
Tell dev-server to watch the files served by the devServer.watchContentBase option.
It is disabled by default.
When enabled, file changes will trigger a full page reload.
Example:
module.exports = {
//...
devServer: {
// ...
watchContentBase: true
}
};
I also had a problem with my devserver which stopping working. Previously it had worked, then I added a ton of extras to get a production build. Then when I came back to devserver it didn't work any more.
Took lots of sleuthing - eventually starting with a prior commit in git, then reintroducing changes one-by-one until I figured it out.
Turns out it was a change I had made to package.json, specifically this line:
"browserslist": "> 1%, not dead",
This was useful to guide postcss, regarding the browsers to target.
But, it stops devserver working. Workaround is to add this to the dev webpack config:
target: 'web',
I found the solution here: https://github.com/webpack/webpack-dev-server/issues/2812
Hope that saves someone a few hours of trouble!
Somehow, for my case, removing "--hot" makes it work. So, I removed hot: true
webpack.dev.js
module.exports = merge(common, {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
publicPath: '/js/',
contentBase: path.resolve(__dirname, 'docs'),
watchContentBase: true,
}
});
webpack.common.js
output: {
path: path.resolve(__dirname, 'docs/js'),
filename: '[name].min.js',
library: ['[name]']
},
I had the same problem and I find that in addition to all those points, we also have to put the index.html together with the output bundle.js in the same folder and set the contentBase to this folder, either the root or a subfolder.
This happened to me as well after running two different applications on the same webpack-dev-server port after one another. This happened even though the other project was shut down. When I changed to a port that had not been used it started working directly.
devServer: {
proxy: {
'*': {
target: 'http://localhost:1234'
}
},
port: 8080,
host: '0.0.0.0',
hot: true,
historyApiFallback: true,
},
If you use Chrome like me then just open Developer Tools and click on Clear site data. You can also see if this is the problem by running the site in incognito mode.
It can happen because of ExtractTextPlugin. Deactive the ExtractTextPlugin in development mode. Use it only for production build.
I experienced a similar situation where webpack-dev-server was serving my index.html file but not updating. After reading a few posts I realized that webpack-dev-server does not generate a new js file but instead injects one into index.html.
I added the html-webpack-plugin to my app and with the following configuration in my webpack.config.js file:
const HtmlWebpackPlugin = require('html-webpack-plugin')
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
]
I then commented out the script tag referencing my entry js file in index.html. I can now run webpack-dev-server without any additional flags and any changes to my files will display in the browser instantly.
What worked for me:
cache: false
https://webpack.js.org/configuration/cache/
My case was that I got so deep into experimenting with Webpack features, but totally forgot that I had set inject to be false the entire time like so...
new HTMLWebpackPlugin({
inject: false,
...
}),
Switching that on was my ticket.
I'll add my own special tale of Webpack --watch woe to the wall of suffering here.
I was running
webpack --watch
in order to build a Typescript project. The compiled .js files would update, but the bundle that the browser was seeing would not. So I was basically in the same position as the OP.
My problem came down to the watchOptions.ignored parameter. The original author of the build config had set up ignored as a filter function, which turns out to not be a valid value for that parameter. Replacing the filter function with an appropriate RegExp got the --watch build working again for me.
What helped me was introducing devServer.devMiddleware. For example, in webpack-dev-server 4.10.0, property contentBase was not available anymore.
devServer: {
devMiddleware: {
index: true,
publicPath: './build/static/',
serverSideRender: true,
writeToDisk: true,
}
},
Your project tree is not clear, however the problem may be in contentBase setting. Try to set contentBase: __dirname