I'm trying to correctly setup webpacks HMR, I'm developing a small app in order to learn how to use Redux in a React application.
I ran into a problem with webpack and the HMR plugin, when implementing the module.hot.accept function everything seems to work fine, but I've noticed it that when I modify a dependency of my App component it only re-renders the view when I don't pass any dependency argument to module.hot.accept as specified in webpack's docs.
This is what the documentation says I should do:
module.hot.accept(
dependencies, // Either a string or an array of strings
callback // Function to fire when the dependencies are updated
)
This is what I'm trying to do, this doesn't work.
module.hot.accept('./components/App', () => {
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
})
module.hot.accept('./reducers', () => {
// Reconfigure the store
})
This one works
module.hot.accept(() => {
// Render function
})
So let's say my App component, the one I render as child of the <Provider> imports a Header component and just renders like so:
const App = () => (
<div>
<Header />
</div>
)
then if I edit Header the browser will only re-render the view if there's no dependency in module.hot.accept
The problem here is that if I don't pass any dependency it will try to reload my store object and that fires this warning: <Provider> does not support changing 'store' on the fly, I want to properly configure webpack so it only updates the store object when I change things on my reducers and the view when I make changes to my components or containers.
* Edit *
Little bit of extra info, webpack seems to be aware of updates bc it logs in console the updated modules, however doesn't rerenders anything.
This is my webpack.config.js
const path = require('path')
const webpack = require('webpack')
const namedModules = new webpack.NamedModulesPlugin();
const hotModuleReplacement = new webpack.HotModuleReplacementPlugin();
const config = {
context: path.resolve(__dirname, 'src'),
entry: './index.jsx',
devtool: 'eval-source-map',
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [{
test: /\.(js|jsx)$/,
include: path.resolve(__dirname, 'src'),
use: [{
loader: 'babel-loader',
options: {
presets: [
['env', {'es2015': {'modules': false}}],
'react'
],
plugins: [
'transform-object-rest-spread',
]
}
}]
}]
},
resolve: {
extensions: ['.js', '.jsx', '.json', '*'],
modules: [
'node_modules'
]
},
plugins: [
namedModules,
hotModuleReplacement
],
devServer: {
port: 9000,
host: 'localhost',
inline: true,
hot: true
}
}
module.exports = config
Thanks in advance, fine developers.
So it was the babel configuration as I thought, you need the option modules: false in the babel configuration so it lets webpack handle the modules, it is a noob mistake but man, it drove me crazy for days.
Turned out I was doing something wrong in this line of the babel presets:
['env', {'es2015': {'modules': false}}]
the correct configuration is:
['env', {modules: false}]
Related
I'm building an app with micro-frontends using webpack 5's module federation plugin. Everything was fine until I started adding react hooks into my remote app. At that point I received errors about "invalid usage of hooks", i.e. I discovered I had TWO versions of react loaded, one from the remote and one from the app consuming the remote.
That problem was solved by adding a shared key to the ModuleFederationPlugin section of my webpack config that marked React as a singleton. Now everything compiles and seems to run just fine.
However, the webpack compiler is throwing some annoying warnings at me now. Its saying:
No required version specified and unable to automatically determine one. Unable to find required version for "react" in description file (/Users/myComputer/Development/myapp/node_modules/#apollo/client/react/context/package.json). It need to be in dependencies, devDependencies or peerDependencies.
Here is what my webpack config (in the remote) looks like currently:
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin')
const deps = require('./package.json').dependencies
module.exports = {
mode: 'development',
devServer: { port: 3001 },
entry: './src/index.tsx',
output: {
path: __dirname + '/dist/',
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
},
use: 'ts-loader',
},
]
},
devtool: 'source-map',
plugins: [
new ModuleFederationPlugin(
{
name: 'myRemote',
filename: 'remoteEntry.js',
exposes: {
'./App':
'./src/App/App.tsx',
},
shared: {
'react': {
singleton: true,
version: deps['react'],
},
'react-dom': {
singleton: true,
version: deps['react-dom'],
},
},
}
),
new HtmlWebpackPlugin({
template:
'./index.html',
})
]
}
The consuming app's webpack config is almost the same, especially the shared section (there are some slight differences in that it declares the remotes).
What would be the way to tell webpack that the apollo package will be getting its react dependency from somewhere else? Or if thats not the right thing to tell webpack, what is and how can I get rid of these warnings?
Fixed my own problem by changing the key version to requiredVersion
I am building a simple React app from scratch using Webpack.
I was finally able to run the dev server and when I tried to apply some styles via CSS, the files wouldn't load and I assume my Webpack 4 configuration is not right.
Here is the code:
webpack.config.js
// const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');
module.exports = {
mode: 'development',
entry: ['./src/index.js'],
resolve: {
extensions: [".js", ".jsx"]
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist',
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 8080
},
module: {
rules: [
{
test: /\.js|.jsx$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: ["react"]
}
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|jpg)$/,
loader: 'url-loader'
}
]
},
};
My project structure is like this, I will include only src because it lives in the root:
**src**
|_assets
|_componentns
|_styles
|_App.css
|_index.css
App.jsx
index.js
index.html
I would like to be able to add multiple css files for each component I have and apply them, and to be able to style the index the index.html.
Thank you very much for your help.
Your webpack configuration looks fine.
make sure you import the required css files in your components.
import "./App.css";
class App extends Component {
render() {
return (
<div>
<Child />
</div>
);
}
}
All you have to do is import the CSS files when needed as you would a JavaScript module. So if you want to have a style sheet for your whole application, you can import a global stylesheet in your index.js.
import './styles/index.css';
and you can do the same for each component with specific styles
import './styles/App.css'
in which case you might want to setup CSS modules to avoid overlapping class names.
Ok, rookie mistake here, the way I ahve set up webpack is I have to build it first and then run the dev server, no the other way around.
All answers above are valid and helpful, I just forgot to run build after changes.
I'd like to use webpack to bundle my JS together for a React component but without including React or React Dom, just my own React code.
The idea is so that I can load React or React Dom separately on the webpage with RequireJS as I'm adding the component to Magento2 which uses this approach for adding JS dependencies. My thought being that if I add another component this way, I don't want to be adding the React Libraries twice.
I think I need to use a different babel loader or pass in some other options?
Here is my webpack.config
const path = require('path');
const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-source-map',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'web'),
filename: 'js/react-component.js',
publicPath: ''
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
}
It works but as I said it includes the full react libraries in the generated js/react-component.js file. Any advice how I can do this?
As #Aaqib pointed out I needed to add this config options to webpack.
externals : {
react: 'react',
reactDom: 'react-dom'
}
Does anyone actually have HMR up and running smoothly? Mine is hot swapping sometimes only. How is that possible? I will edit a line of text and it will swap. Then I will go edit the same text and it will not see it. I'm using webpack 1.14. I've spent way too much time on this searching every example online and redoing and configuring my webpack.config. This thing is tough without some real documentation on exactly how to set it up with a webpack-dev-server that works everytime. With all of the unanswered questions on stackOverflow and the webpack GitHub issues section, you'd think nobody really understands it except for the creators and a few gurus.
I have a webpack config that looks like this:
var config = {
entry: [
'webpack-dev-server/client?http://localhost:8080',
// bundle the client for webpack-dev-server
// and connect to the provided endpoint
'webpack/hot/only-dev-server',
// bundle the client for hot reloading
// only- means to only hot reload for successful updates
DEV + "/index.jsx"],
output: {
path: OUTPUT,
filename: "app.js",
publicPath: '/',
},
devtool: 'inline-source-map',
devServer: {
hot: true,
// enable HMR on the server
contentBase: OUTPUT,
// match the output path
publicPath: '/'
// match the output `publicPath`
},
plugins: [
new ExtractTextPlugin('styles.css'),
new webpack.NamedModulesPlugin(),
/* new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin()*/
],
module: {
loaders: [
{
test: /\.jsx?$/,
include: DEV,
loaders: ["react-hot", "babel-loader"],
},
{
test: /\.css$/,
loader: 'style-loader'
}, {
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
],
}
};
module.exports = config;
My file structure is:
-> EZTube
-> dev
->TabComponent
->other source code files
->index.jsx
-> output
->app.js
->index.html
->styles.css
-> webpack.config.js
-> package.json
My index.jsx looks like:
import React from "react";
import ReactDOM from "react-dom";
import TabComponent from './TabComponent/TabComponent.jsx';
import { AppContainer } from 'react-hot-loader';
ReactDOM.render(
<TabComponent />,
document.querySelector("#container")
);
if (module.hot) {
module.hot.accept('./TabComponent/TabComponent.jsx', () => {
const NewApp = require('./TabComponent/TabComponent.jsx').default
ReactDOM.render(NewApp)
});
}
The weird thing is sometimes hot swap happens when I make a change. Other times not at all. Just wondering if there was some wise internet sage out there who would understand why that is happening with the current set up.
I was having the same intermittent HMR problem, though I'm using
webpack-dev-middleware
webpack-hot-middleware
As HMR was working sometimes, I suspected the diffs were not always getting detected.
I'm running this on Windows, so I tried adding this configuration
watch: true,
watchOptions: {
aggregateTimeout: 300,
poll: 1000, //seems to stablise HMR file change detection
ignored: /node_modules/
},
https://webpack.js.org/configuration/watch/
My HMR is more consistently detected now.
I'm trying to setup hot module reloading in a react/typescript (with TSX) environment. I have used the react/redux real-world example as a model in getting things going, and this is what I have so far:
server.js
var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpackHotMiddleware = require('webpack-hot-middleware')
var config = require('./webpack.config')
var app = new (require('express'))()
var port = 3000
var compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }))
app.use(webpackHotMiddleware(compiler))
app.use(function(req, res) {
res.sendFile(__dirname + '/index.html')
})
app.listen(port, function(error) {
if (error) {
console.error(error)
} else {
console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
}
})
webpack.config.js
var path = require('path')
var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
path.resolve('./src/index.tsx'),
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({ template: './index.html' })
],
module: {
loaders: [
{ test: /\.tsx?$/, loader: 'ts-loader' }
]
},
resolve: {
extensions: ['', '.ts', '.tsx', '.js', '.json']
},
}
index.tsx
import * as React from 'react';
import { render } from 'react-dom';
import Root from './containers/root';
render(
<Root />,
document.getElementById('root')
);
containers/root.tsx
import * as React from 'react';
export default class Root extends React.Component<void, void> {
render(): JSX.Element {
return (
<p>boom pow</p>
);
}
}
Changing <p>boom pow</p> to <p>boom boom pow</p> in the root element kicks off this in the javascript console in the browser:
[HMR] bundle rebuilding
client.js?3ac5:126 [HMR] bundle rebuilt in 557ms
process-update.js?e13e:27 [HMR] Checking for updates on the server...
process-update.js?e13e:81 [HMR] The following modules couldn't be hot updated: (Full reload needed)
This is usually because the modules which have changed (and their parents) do not know how to hot reload themselves. See http://webpack.github.io/docs/hot-module-replacement-with-webpack.html for more details.
process-update.js?e13e:89 [HMR] - ./src/containers/root.tsx
process-update.js?e13e:89 [HMR] - ./src/index.tsx
I've stepped through these steps as best I can tell, but am still having no luck.
What am I missing?
The problem, as mentioned by commenters, was missing in my loader - I'm not sure if this had anything to do with it, but I also switched to using babel after typescript - and having typescript compile to ES6. New config below:
var path = require('path')
var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
path.resolve('./src/index.ts'),
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({ template: path.resolve('./src/index.html') })
],
module: {
loaders: [
{ test: /\.tsx?$/,
loaders: [
'react-hot',
'babel?presets[]=es2015',
'ts-loader'
]
},
{ test: /\.json$/,
loader: 'json'
}
]
},
resolve: {
extensions: ['', '.ts', '.tsx', '.js', '.json']
},
}
if someone still struggles with this see the readme: https://github.com/webpack-contrib/webpack-hot-middleware/blob/master/README.md
This module is only concerned with the mechanisms to connect a browser client to a webpack server & receive updates. It will subscribe to changes from the server and execute those changes using webpack's HMR API. Actually making your application capable of using hot reloading to make seamless changes is out of scope, and usually handled by another library.
webpack-hot-middleware doesn't handle hot reload, you'd need to use react-hot-loader for example