I know the title doesn't make too much sense. But please bear with me.
I am setting up React for a legacy Rails app which is using the good old static ERBs. Due to the scale, I have to move towards SPA slowly, meaning swapping out components on the page.
My current setup is using webpack to compile a bundle file, the output it to the assets directory. Then just load that bundle file on the page relying on assets pipeline for caching (not idea, but enough to get started). On pages that have react component, I will have a <div> for appending a certain component. e.g.:
<body>
<div>some other erb, html stuffs</div>
<div>more other erb, html stuffs</div>
<div id='react-component-1'></div>
<div id='react-component-2'></div>
</body>
This works as a basic setup. But to speed up the development, I'd like to setup hot loading. However, because I am not serving the entire page, I have to actually write the bundle file to disk so that rails can pick it up. And this also prevent me from using webpack-dev-server.
Is there any way to setup HMR in this setup?
Possible options:
Reloading the bundle file every now and then (but I've tried this by appending new script tag, and removing the old one. Although the script file is downloaded (200 status from network tab), the updated scripts are not being loaded)
Refreshing the page programmatically, and store serialize state in session storage (this won't be ideal, because it also refreshes other parts of the static page)
Maybe there is a way to serve only the bundle file through webpack-dev-server?
Edit
I followed #SamHH answer and it seems it's not able to load the bundle file (404). My path config is a little quirky.
I have my webpack output path to
'../../app/assets/webpack/admin'
publicPath to
/admin/
But a matching path set in proxy option didn't quite work. And from network tab, looks like it was loading from /javascripts/...
Webpack config:
const config = {
entry: {
bundle: './apps/appsRegistration',
vendor: VENDOR_LIBS
},
output: {
filename: '[name].js',
path: pathLib.resolve(__dirname, '../../app/assets/webpack/admin'),
publicPath: '/admin/'
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor'
}),
],
module: {
rules: [
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/,
},
],
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
redux: 'Redux',
'react-redux': 'ReactRedux',
'redux-thunk': 'ReduxThunk'
},
devServer: {
port: 9000,
disableHostCheck: true,
proxy: {
'!/admin/**': {
target: 'http://localhost:3000',
secure: false
}
},
hot: true
}
};
You can use webpack-dev-server and proxy all non-assets back to your Rails app. So if your rails app is on http://localhost:8000, you tell the Webpack config to proxy all devServer requests that don't match your assets glob back to that address. Then you would load and develop on the Webpack dev server port.
For example, if you set your Webpack config as follows output.publicPath: '/dev-assets/' then you can do the following:
devServer: {
port: 9000,
proxy: {
'!/dev-assets/**': {
target: `http://localhost:8000`,
secure: false
}
},
hot: true
},
}
Then just load http://localhost:9000 when developing.
Related
I am building electron/angular app - its working fine;
I have another nodejs script that open socket.io server; (I am using typescript + webpack for creating all files in a single bundle js file).
I am trying to include this script inside the anguler/electron. But its looks like socket.io (or some others included libraries in the script) depends on nodejs built-in packages and its not possible to use it in the angular application. That makes sense for me because you cant start socket server on the browser directly - but its a desktop eletron app.
This error appears when I am trying to build the angular app for packages:
path, os, http, https, crypto, tty, zlib, util
Error: Module not found: Error: Can't resolve 'util' in '..\src\app'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "util": require.resolve("util/") }'
- install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "util": false }
webpack.config of the nodejs script
const path = require('path');
module.exports = {
entry: './src/index.ts',
mode: 'production',
target: 'node',
module: {
rules: [
{
test: /\.ts?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
output: {
filename: 'script.min.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'umd',
libraryExport: 'default'
},
};
I could include this script not inside the angular app but inside the main.js where is the electron app starting from ... but this way I will not have access to the content in the script from Angular inside;
Where I am failing in this logic?
The wanted result is an electron/angular desktop app where I have a button and when click it its start socket.io server with provided Configurations.
You can fix this by simply adding this to your webpack config. I don't use Angular but in React I add this to webpack.renderer.config.js I would recommend reading about creating a secondary windows in Electron and run all of these things though.
resolve: {
// all your other configs
fallback: {
"util": false,
}
}
I am trying to setup webpack's dev server and HMR to work with Shopify theme development. When running the server and opening the local IP, I get this error from Shopify's DNS provider, CloudFlare.
How can I properly setup webpack to inject hot changes (css/JS) to my proxied Shopify store (the mystore.myshopify.com url)?
My webpack config as follows:
const path = require("path");
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
mode: "development",
devServer: {
contentBase: false,
hot: true,
https: true,
proxy: {
"**": {
target: "http://mystore.myshopify.com",
secure: false
}
},
},
entry: "./src/scripts/index.js",
output: {
filename: "./app.js",
path: path.resolve(__dirname, "dist")
},
plugins: [
],
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
//postcss here (autoprefixer, babel etc)
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
};
My proposed solution for hot reloading with webpack and shopify.
In your package.json you will want the following scripts
A webpack build script that watches for changes. I have also added a progress parameter so I can see when it updates. This will be watching your /src folder for changes.
"webpack:build": "cross-env NODE_ENV=development webpack --watch --progress",
A shopify theme serve script that uploads the theme files from a /dist folder that is the output of a webpack build.
"shopify:serve": "cd dist && shopify theme serve"
You can link these two scripts together into one using the following.
"deploy:serve": "run-p -sr webpack:build shopify:serve"
So what happens is the webpack build script listens for changes in your /src code. When a change is main it re-builds the output to the /dist folder that shopify theme serve is listening on. When that updates, shopify uploads the changes.
Voila.
Here is the repo for this implementation if you want to play around - https://github.com/Sambuxc/9119-shopify-theme/
As of writing this, my dev versions are:
Node 18.7.0
Npm 8.15.0
Shopify Cli 2.21.0
Good luck and I hope this helps future developers.
Please reach out to me with any further questions if you get stuck.
I am trying to use Python Flask with a React Frontend. Here is my webpack file:
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: [
"./js/app.jsx",
"./scss/main.scss"
],
output: {
path: __dirname + '/static',
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
},
exclude: /node_modules/
},
{ // sass / scss loader for webpack
test: /\.(sass|scss)$/,
loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
}
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new ExtractTextPlugin({ // define where to save the file
filename: '[name].bundle.css',
allChunks: true,
})
]
};
I am not sure if this file is the problem, but for some reason, my app is not hot-reloading. Here is a simple repo that I setup for which hot reloading does not work: https://github.com/rishub/Flask_React
I am using
webpack version: 3.8.1,
node version: 6.11.5,
npm version: 3.10.10
I cannot seem to figure out why it is not reloading.
I run python app.py in one terminal and webpack --watch in the other.
The terminal with webpack seems to detect the changes to the React jsx files, however, the app does not reload on the browser unless I force refresh, even a regular refresh does not work.
If someone would be able to point out the problem or fork/make a PR to the repo, that would be great
With watch, you're only compiling the updates themselves & not interfacing with the application.
--watch is not a flag for hot reloading in your browser. It regulates registered files for changes and recompiles the Webpack output whenever there is a change within those files. However, it does not necessarily forward that output to the browser.
Your force refresh was syncing up with the new version served up by Webpack, and also disrupting the browser cache.
Hot Module Reloading needs to be done with some kind of additional tool like Webpack HMR and a configured Webpack Dev Server.
From the docs, Hot Reloading entails all of the following:
The application asks the HMR runtime to check for updates.
The runtime asynchronously downloads the updates and notifies the application.
The application then asks the runtime to apply the updates.
The runtime synchronously applies the updates.
I have a React based application, running off a NodeJS based server, and would like to allow it to download a non-static file, without the use of xhr.
I am thinking of using Express, but I am not sure how I would make it co-exist with React in the same container? Can anyone suggest how I would go about this? I am still learning webpack and React, and I having trouble finding examples of this?
The React server is started via webpack:
node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --host 0.0.0.0 --port 8081 --hot --inline
With the webpack-dev-server.js, looking as follows:
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
The './src/index.js' is React type code.
Disclaimer: I've never used webpack-dev-server extensively myself (at least not directly), but I can think of two solutions.
One is to use setup in the webpack-dev-server configuration. As stated here:
setup: function(app) {
// Here you can access the Express app object and add your own custom middleware to it.
// For example, to define custom handlers for some paths:
// app.get('/some/path', function(req, res) {
// res.json({ custom: 'response' });
// });
}
Alternatively, which is a method I use myself, is to use webpack-dev-middleware, which is a middleware for Express. So basically, you create your own Express server that has the same functionality as webpack-dev-server.
Here's an excerpt from one of my projects (where app is the Express app instance):
// Webpack (only when not running in `production` mode):
if (process.env.NODE_ENV !== 'production') {
debug('setting up webpack middleware');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpackConfig = require('./webpack.dev');
const compiler = require('webpack')(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
noInfo : true,
publicPath : webpackConfig.output.publicPath
}));
app.use(webpackHotMiddleware(compiler));
}
In addition to #robertklep's answer, based on some further research, you can 'compile' your React project and then just make use of those resources without nodejs.
Use node & webpack to 'compile' your project:
node node_modules/.bin/webpack
This will create a bundle.js file which contains the compiled project. Other files, such as the images, external Javascript and stylesheets will need to be copied, for example (assuming there is a dist folder):
cp bundle.js dist/
cp index.html dist/
cp -rf img css frameworks dist/
Everything in the dist folder then can be served via a traditional web server, such as Nginx or Apache, with NodeJS.
I've set up a basic react application with webpack but I couldn't get the webpack-dev-server running properly.
I've installed webpack-dev-server globally and tried running the command sudo webpack-dev-server --hot as hot reloading was required.
The project seems to be working fine with just webpack cmd. It builds into my build folder and I can get it working via some server but it wont work with webpack-dev-server. From terminal its clear that the build process has completed with no error being thrown [webpack: bundle is now VALID.] and its in fact watching properly because on any change it does trigger the build process but it doesn't really gets built [it doesn't serve my bundle.js]. I tried changing the entire config and still couldn't get the issue resolved.
It would be much appreciated if someone can help.
Following is my webpack.config.js file.
var path = require('path');
module.exports = {
devtool: '#inline-source-map"',
watch: true,
colors: true,
progress: true,
module: {
loaders: [{
loader: "babel",
include: [
path.resolve(__dirname, "src"),
],
test: /\.jsx?$/,
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'react', 'stage-0'],
}
}, {
loader: 'style!css!sass',
include: path.join(__dirname, 'src'),
test: /\.scss$/
}]
},
plugins: [],
output: {
path: path.join(__dirname, 'build/js'),
publicPath: '/build/',
filename: '[name].js'
},
entry: {
bundle: [
'./src/index.js'
]
},
devServer: {
contentBase: "./",
inline: true,
port: 8080
},
};
I've got the issue resolved by myself. Silly as it sounds but the issue was with the publicPath under the output object. It should match the path property instead of just /build/, i.e.,
output: {
path: path.join(__dirname, 'build/js'),
publicPath: '/build/js', // instead of publicPath: '/build/'
filename: '[name].js'
},
In my case I had to check where the webpack is serving the file.
You can see it:
http://localhost:8080/webpack-dev-server
Then I could see my bundle.js path > http://localhost:8080/dist/bundle.js
After that I used that /dist/bundle.js in my index.html <script src="/dist/bundle.js"></script>
Now it refreshes any file changes.
webpack-dev-server serves your bundle.js from memory. It won't generate the file when you run it. So bundle.js is not present as a file in this scenario.
If you wan't to use bundle.js, for example to optimize it's size or test your production deployment, generate it with webpack using the webpack command and serve it in production mode.
By the way, started from Webpack v4 it is possible to write in-memory assets to disk:
devServer: {
contentBase: "./",
port: 8080,
writeToDisk: true
}
See doc.
The fix to this for me was:
devServer: {
devMiddleware: {
writeToDisk: true,
}
}
https://webpack.js.org/configuration/dev-server/#devserverwritetodisk-
Dev-server keeps the compiled file in memory, and I can't access it directly...
BUT! THE SOLUTION is that you have no need to access it, in development(even when you run your project on node server or localhost) use localhost:8080 to access your page, and that's where webpack-dev-server is serving your page and you can feel all advantages of using it(live reload!), BUT! it doesn't compile your bundle.js, SO! before production, you need to manually run webpack build command, and that's it! there is no way for dev-server to compile your bundle.js file! Good Luck!
Please refer to this - https://github.com/webpack/webpack-dev-server/issues/24
According to this, webpack dev server no longer writes to the disk. So, you wont be able to see the build file. Instead, it will be served from the memory. To get it working you have to set the proper path.
Example: in index.html loads the build file from '/dist/main.js' so in webpack config file set the output.publicPath to '/dist/'
In my case I was using VS Code and I had to restart it. I have noticed that vs code bugs up sometimes. The changes you make in configuration files (package.json, webpack.config.js etc.) do not take effect sometimes. So, in case you encounter a situation where something doesn't work even with the correct settings, just restart vs code.
I can't see any bug reports related to this. So that's strange. I'm thinking this bug is triggered if you change one of the configuration files some time later after you have already built the project multiple times.
If this is actually what's happening then it's a huge bug. I'll try switching to Visual Studio instead of Code and see if this still happens. If it does then it's probably an issue with webpack.