Hello i have a problem with react-router, my code
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={StartPage}/>
<Route path="/matches" component={MatchesPage} />
<Route path="/sector/:idparam" component={SectorsPage} />
</Route>
</Router>
</Provider>,
app);
When I call /matches everything is OK, but when i try GET /sector/15 app failed try to load http://localhost:8080/sector/client.min.js but normally will load from default path (/)
Webpack:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/client.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
}
]
},
output: {
path: __dirname + "/src/",
filename: "client.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({mangle: false, sourcemap: false}),
],
devServer: {
historyApiFallback: true,
contentBase: './',
hot: true
},
};
I don't think the issue is with react router, or even webpack. I think your issue is related to how you are requiring your client js file, although since you didn't include that section of code I cannot confirm.
It looks like you are including the script relative to your path
(<script src="client.min.js"></script> no leading slash) instead of an absolute path (<script src="/client.min.js"></script>).
Related
Hello i am stuck with this one and couldnt figure it out. So i have React router v6 with basename - "/ui/" , and i want that when i open localhost:8080 that it automatically turns into "localhost:8080/ui/" because the real view is actually rendered in /ui/ route.
Router setup:
<BrowserRouter basename="/ui/">
...routes here
</BrowserRouter>
Webpack dev:
module.exports = {
mode: 'development',
devtool: 'cheap-module-source-map',
devServer: {
hot: true,
historyApiFallback: true,
open: true,
port: 6969
}
}
And common webpack:
module.exports = {
entry: path.resolve(__dirname, '..', './src/index.tsx'),
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader"
]
},
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
type: 'asset/resource',
},
{
test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
type: 'asset/inline',
},
],
},
output: {
path: path.resolve(__dirname, '..', './build'),
filename: 'bundle.js',
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '..', './src/public/ui/index.html'),
}),
],
stats: 'errors-only',
}
I have tried to add to output publicPath: '/ui/' but it didnt work.
Or even something like this:
static: [
{
publicPath: '/',
directory: path.join(__dirname, "../public/ui/"),
}]
How i can achieve this withouth "redirecting" :\
Try this solution
<Route exact path="/">
<Redirect to="/home" />
</Route>
Check your main.js or similar in your src or sources.
Mine had:
const Root = () => (
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
{appRoute}
</Route>
</Router>
</Provider>
);
and so just had to move it to Route path="/ui/" component={App}
code repository url
below is my file structure
and webpack.config.js looks like something like below
const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const entryPoint = path.join(__dirname, "src", "index.js");
module.exports = {
entry: entryPoint,
output: {
path: path.join(__dirname, "public"),
filename: "bundle.js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: path.join(__dirname, "public", "index.html"),
filename: "./index.html",
}),
],
devServer: {
contentBase: path.join(__dirname, "public"),
historyApiFallback: true,
// publicPath: "/dist/",
},
devtool: "source-map",
stats: {
errorDetails: true,
},
};
i don't know why is it still not working eventhough i have give historyApiFallback
below is my app.js
when i click on the /home route the content is not changing.
could any one please explain me what more i have to add
and my index.js
You need to add exact to your / route otherwise it will match anything starting with / and since it is in a Switch it will be the only one to be matched.
<Switch>
<Route exact path="/" component={() => <div>i am in home</div>} />
<Route exact path="/home" component={() => <div> i am user</div>} />
</Switch>
If the url is not parameterized, i would add exact to /home as well
See: https://reactrouter.com/web/api/Route/exact-bool
so I'm having a problem with webpack codesplitting. It creates bundles correctly but then everything is getting messed up when it sends xhr request for the bundle. Only the index route works correctly 'cause it's just a / but it actually uses client side route as path to bundle. So using the example below it goes with the path localhost:3000/dir/something/0.bundle.js instead of localhost:3000/0.bundle.js. I'm new to webpack, is there a way to make it use the / route every time?
pseudo markup
<Link to="/dir/something/else"/>
<!-- <App/> -->
<BrowserRouter>
<Switch>
<Route path="/dir/:param1/:param2">
<Bar/>
</Route>
<Route path="/">
<Foo/>
</Route>
</Switch>
</BrowserRouter>
I'm using #loadable/component so each component is imported with a loadable(()=>import('path/to/component'))
webpack.config.js
{
mode,
entry: './src/index.tsx',
target: 'web',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.bundle.js'
},
module: {
rules: [
{
test: /\.ts(x)?$/,
use: 'ts-loader',
exclude: /node_modules/,
include: path.join(__dirname, '/src'),
},
{
test: /\.svg$/,
use: {
loader: 'url-loader',
options: {
limit: 5000
}
}
}
],
},
devServer: {
hot: true
},
plugins: [new HTMLWebpackPlugin({
template: 'src/index.html'
})],
resolve: {
modules: ['node_modules'],
extensions: ['.ts', '.tsx', '.js', '.json']
}
}
Developing a react app with webpack, in my app.js router when i specify the route to be /foo the component renders normally but when i specify a route as /foo/bar i get the following error
"The resource from “http://localhost:9000/foo/bar/bundle.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)"
App.js
function App() {
return (
<div className="App">
<BrowserRouter>
<Router history={history}>
<Switch>
<Route exact path="/api/login" component={Login} /> //gives error
<Route exact path="/login" component={Login} /> //renders normally
<Route component={Error} />
</Switch>
</Router>
</BrowserRouter>
</div>
);
}
Webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.resolve(__dirname, 'src/index'),
output:{
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module:{
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['#babel/react']
}
}
]
},
{
test: /\.css$/,
exclude: /node_modules/,
use:[
{loader: 'style-loader'},
{loader: 'css-loader'}
]
},]
},
devServer:{
contentBase: path.resolve(__dirname, 'dist'),
port: 9000,
historyApiFallback: true
},
plugins:[
new HtmlWebpackPlugin({
template: "src/index.html"
})
]
};
I was facing the same issue and solved it by adding publicPath: '/dist/' in the output option of module.exports in webpack.config.js.
Try to change the content-type to 'text/javasscript'.
content-type: "text\javasscript"
I am trying to set up my routers for my app, and have the basic / entry point working (seemingly). It seems when I try to start adding sub routes, it is breaking. I have a pretty straight forward set up right now. I am using react + redux and my render looks like :
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory} >
<Route path="/" component={comp1.Component}>
<Route path="test" component={comp2.Component} />
</Route>
</Router>
</Provider>,
// eslint-disable-next-line no-undef
document.getElementById('app')
);
I am running webpack dev server on localhost:8080, and it serves the first route with no problem, however when I go to localhost:8080/test, I am getting a Cannot GET /test .
Here is my webpack config:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./client/app.jsx'
],
output: {
path: path.join(__dirname, ''),
filename: 'bundle.js',
publicPath: '/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
],
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel-loader",
include: __dirname,
query: {
presets: [ 'es2015', 'react', 'react-hmre' ]
}
}]
}
}
Unsure what I am doing wrong here, would be grateful for any help. Thanks!
React Router uses the HTML5 history API. This means that 404 responses need to serve /index.html.
The docs mention how this works. You need to add this to your module.exports object:
devServer: {
historyApiFallback: true
}
Note that this only works for the CLI, when using the Node.js API you need to add this as a second parameter:
var server = new WebpackDevServer(compiler, { historyApiFallback: true });