I have express ssr app. I want to host my static files in /static/* folder. But i have problem with React.Lazy component chunk request, it has wrong path
http://localhost:3000/staticreact.LazyChunk.js
My server code:
import express from 'express';
import path from 'path';
import handleRequest from '#server/infrastructure/handleRequest/handleRequest';
import {routes} from '#general-infrastructure/routes/routes';
import { handleErrors } from '#server/middlewares/errorHandler/errorHandler';
const server = express();
// if i'll comment this, reactlazy chunk will have normal path, but other static files will have 404 error status
server.use('/static', express.static(path.join(__dirname, '/static')));
// TODO -
// 5. redux for theme
server.get('*', handleErrors(async function(req, res, next) {
handleRequest(req.url, res, routes);
}));
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
if i'll comment server.use , reactlazy chunk will have normal path, but other static files will have 404 error status.
How can i fix it? ty
Noone extra slash not working
Webpack config:
module.exports = {
name: 'client',
entry: {
client: path.resolve(__dirname, 'src/client/index.tsx'),
},
mode: mode,
output: {
path: path.resolve(__dirname + '/dist/static'),
filename: '[name].[contenthash].js',
publicPath: path.resolve(__dirname, '/static'),
chunkFilename: 'react.[name].chunk.js',
clean: true,
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.css', '.scss'],
alias: webpackAliases,
},
Noone extra slash in webpack config not working
Router:
const Lazy = React.lazy(() => import(/* webpackChunkName: "LazyChunk" */ '#client/modules/pages/Lazy'));
const Routes: React.FC = () => {
const AppRoutes = useRoutes(
[
{path: '/', element: <Feed />},
{path: '/lazy', element: <Lazy />},
{path: '/overview', element: <Overview.component />},
],
);
return (
<Suspense fallback="Loading...">
{AppRoutes}
</Suspense>
);
};
React lazy load chunk error:
publicPath
the value of this option ends with /
Try adding /
publicPath: path.resolve(__dirname, '/static') + '/',
try to use only this,
server.use(express.static("/static"));
Related
I am trying to deploy a website with a basic express server(inexperienced with it obviously) when I use a node dev server it works fine but when I use node server.js i get this error
Uncaught SyntaxError: Cannot use import statement outside a module
So I have a main.js with imports as follows:
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import { defaults as defaultControls } from 'ol/control';
I have my basic server.js
const express = require('express');
const path = require('path');
const port = process.env.PORT || 3003;
const app = express();
app.use(express.static(__dirname));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, './frontend/index.html'));
});
app.listen(port);
Start script
"start": "node server.js",
and webpack config
module.exports = {
entry: './main.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: './main.js'
},
devtool: 'source-map',
devServer: {
port: 3003,
clientLogLevel: 'none',
stats: 'errors-only'
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new CopyPlugin([{from: 'data', to: 'data'}]),
new HtmlPlugin({
template: './frontend/index.html'
})
]
};
folder structure
frontend -index.html
-page2.html
main.js
package.json
webpack
...
Hi I am trying to establish my project in react.
My Current project structure is
-public
--w
---dist
----bundle.js
---index.html
-server
--server.js
-src
--app.js
-webpack.config.js
-package.json
-.babelrc
I am using node js as server
I want my static files to called on localhost:port//w/
and api call on localhost:port//api/
I have tried manipulating server.js, routes, project structure and webpack.config but could not get success.
server.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
const publicPath = path.join(__dirname, '../public/w');
app.use(express.static(publicPath));
app.get('/w/*', (req, res) => {
console.log('Calling..');
res.sendFile(path.join(publicPath, 'index.html'));
})
app.get('/api/test', (req, res) => {
res.send("Hello");
})
app.listen(port, () => {
console.log(`Server is up on ${port}`);
})
webpack.config
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public', 'w', 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
devtool: 'inline-source-map',
devServer: {
contentBase: path.join(__dirname, 'public', 'w'),
publicPath: '/dist/',
historyApiFallback: true
}
}
My routes
const AppRouter = (props) => {
return (
<BrowserRouter>
<div>
<Switch>
<Route path="/" component={Dashboard} />
<Route path="/w/resume-builder" component={ResumeBuilder} />
</Switch>
</div>
</BrowserRouter>
)
}
Can anyone suggest what should I do or What I am missing in it?
You have to do some restructure
-public
--dist
---bundle.js
--index.html
-server
--server.js
-src
--app.js
-webpack.config.js
-package.json
-.babelrc
Server.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
const publicPath = path.join(__dirname, '../public');
app.use(express.static(publicPath));
//keep all api before fallback
app.get('/api/test', (req, res) => {
res.send("Hello");
});
app.get('/w/*', (req, res) => {
console.log('Calling..');
res.sendFile(path.join(publicPath, 'index.html'));
});
app.listen(port, () => {
console.log(`Server is up on ${port}`);
});
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public', 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
devtool: 'inline-source-map',
devServer: {
contentBase: path.join(__dirname, 'public'),
publicPath: '/dist/',
historyApiFallback: true
}
}
You can keep your routes same.
I'm trying to set up HMR with my express sever. When I run node app, I see that webpack compiles, SQL seeds DB and node runs in my terminal . My app runs and seems to work, however when I make a change I don't see the change. I also don't see the change when I refresh the app either!
What am I missing? I think I'm close.
note: I'm following : http://andrewhfarmer.com/understanding-hmr/
index.js:
import React from 'react'
import ReactDOM from 'react-dom'
import routes from './config/routes'
ReactDOM.render(
routes,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept();
}
webpack.config
var webpack = require('webpack')
var ExtractTextPlugin = require("extract-text-webpack-plugin")
var HtmlWebpackPlugin = require('html-webpack-plugin')
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/index.html',
filename: 'index_bundled.html',
inject: 'body',
})
module.exports = {
entry: {
"jquery": __dirname + '/public/js/lib/jquery/jquery-2.0.3.min.js',
"bootstrap": __dirname + '/public/bootstrap/js/bootstrap.min.js',
"index": [__dirname + '/app/index.js',
'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=2000&overlay=false'],
},
output: {
path: __dirname + '/public',
filename: '[name].js',
publicPath: '/',
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
{test: /\.css$/, loader: 'style!css?sourceMap&modules&localIdentName=[name]__[local]___[hash:base64:5]'},
],
},
devtool: 'cheap-module-inline-source-map',
plugins: [
HTMLWebpackPluginConfig,
new ExtractTextPlugin("dist/[name].css"),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
}
app.js
var express = require('express');
var webpack = require('webpack');
var webpackDevMiddleware = require("webpack-dev-middleware");
var webpackHotMiddleware = require("webpack-hot-middleware");
var compiler = webpack(require("./webpack.config.babel.js"));
/* Sequelize stuff */
var app = module.exports = express();
app.use(webpackDevMiddleware(compiler, {
hot: true,
filename: 'index.js',
publicPath: '/',
stats: {
colors: true,
},
historyApiFallback: true,
}));
//app.use(require("webpack-hot-middleware")(compiler));
app.use(webpackHotMiddleware(compiler, {
log: console.log,
path: '/__webpack_hmr',
heartbeat: 2000,
}));
/* APIs and routes */
// Starting express server
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
I'm working on some markdown editor for my react project.
I wanna use CodeMirror as the code editor, but it seems it does not working when I build it with webpack.
If be honest, CodeMirror are in the DOM-tree, textArea is hidden, but everything I see is:
and
UPD: The same code works perfect on codepen. I guess it's a problem with webpack.
some code:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Editor} from './components';
const rootElement = document.getElementById('root');
ReactDOM.render(<Editor />, rootElement);
components/editor.js
import React, { Component } from 'react';
import cm from 'codemirror';
require('codemirror/mode/markdown/markdown');
export class App extends Component {
componentDidMount() {
this.codeMirror = cm.fromTextArea(this.refs.editor, {mode: 'markdown'})
}
render() {
return (
<div>
<textarea ref='editor' autoComplete='off' defaultValue='default value' />
</div>
);
}
}
server.js
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var HOST = 'localhost';
var PORT = 3000;
var app = express();
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, '/app/index.html'));
});
app.listen(PORT, HOST, function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://' + HOST + ':' + PORT);
});
and webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-hot-middleware/client',
'./app/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'app')
}]
}
};
In webpack gitter chat #bebraw answered to my question:
Codemirror works with webpack but it takes some extra setup. you need
to bring some css etc. for it to render. example
I tried using webpack-dev-middleware as a middleware.
I bundles in memory as it should and serves the JS output file,
but it doesn't hot reload when I save.
any ideas?
You'll want to use https://www.npmjs.com/package/webpack-hot-middleware or something similar.
You should use webpack-hot-middleware. here is a working example. I hope it helps.
for your webpack config (lets call it webpack.config.dev):
const path = require('path');
const webpack = require('webpack');
const distPath = path.resolve(__dirname, '../dist');
const srcPath = path.resolve(__dirname, '../src');
module.exports = {
context: srcPath,
target: 'web',
entry: [
'react-hot-loader/patch',
// activate HMR for React
// bundling the client for webpack-dev-server
// and connect to the provided endpoint
'webpack-hot-middleware/client',
'./client/index.js'
// the entry point of your app
],
output: {
filename: 'app.js',
// the output bundle
path: distPath,
publicPath:'/static/',
// necessary for HMR to know where to load the hot update chunks
pathinfo: true
},
module: {
rules: [
// eslint checking before processed by babel
{test: /\.js$/, enforce: 'pre', loader: 'eslint-loader', exclude: /node_modules/},
// babel
{test: /\.js$/, use: [{loader: 'babel-loader'}], exclude: /node_modules/}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
// enable HMR globally
new webpack.DefinePlugin({ "process.env": { NODE_ENV: '"development"' } })
]
};
For the server (called index.dev.js):
import path from 'path';
import express from 'express';
import React from 'react';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import { renderToString } from 'react-dom/server';
// the above file
import webpackConfig from '../../webpack/webpack.config.dev';
// myown react Html component
import Html from '../server/Html';
const app = express();
app.use(express.static(path.join(__dirname, '..', './public')));
const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
quiet: true,
noInfo: true,
publicPath: webpackConfig.output.publicPath,
stats: { colors: true }
}));
app.use(webpackHotMiddleware(compiler));
app.get('*', (req, res) =>
res.status(200).send(`<!doctype html>${renderToString(
<Html />)}`
// This is my own Html react component. You can send a static html file here as well.
)
);
app.listen(3000, (err) => {
if (err) {
console.error(err);
return;
}
console.info('Demo app listening on port 3000');
});
At the end I call it using babel-watch:
"scripts": {
"start:dev": "rm -f ./dist/* && ./node_modules/.bin/babel-watch ./src/server/index.dev.js -w ./src/server",
},