Webpack React Default URL - reactjs

I am trying to figure out how to set the config up to by default load a different url as the base. Currently it is loading localhost:3000 - I need it to load localhost:3000/market. Client doesn't want the base path to work. For example if this was google, http://google.com wouldn't work and only http://google.com/market would.
I have checked quite a few stacks and this React with webpack was the closest I could find, however I can't use flags for the different environments, so I need it in the config, and I cannot for the life of me figure that out.
This is what I have in my webpack so far:
const appConfig = {
version: pkg.version,
basePath: process.env.BASE_URL,
api: {
baseUrl: `${process.env.BASE_URL}/api`,
},
auth: {
name: "ping",
config: {
clientId: process.env.CLIENT_ID,
authorizationUri: "redacted",
scopes: process.env.SCOPES,
},
},
};
module.exports = {
entry: './src/index.tsx',
output: {
path: path.join(__dirname, 'build/'),
filename: 'marketplace2.js',
globalObject: 'this',
publicPath: '/',
},
mode: nodeEnv,
resolve: {
plugins: [newTsConfigPathsPlugin],
extensions: ['.tsx', '.ts', '.js'],
},
target: 'web',
devServer: {
static: path.join(__dirname, './src'),
open: true,
port: 3000,
},
module: {
rules: [
{
test: /\.(js|jsx|json)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: ['ts-loader'],
},
{
test: /\.(css|scss)$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.(jpg|jpeg|png|gif|mp3|svg|webp|ico)$/,
exclude: /node_modules/,
use: ['file-loader?name=[name].[ext]'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, './public', 'index.html'),
favicon: path.join(__dirname, './public', 'favicon.ico'),
manifest: path.join(__dirname, './public', 'manifest.json'),
}),
new Dotenv(),
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify(nodeEnv),
"process.env.SERVER": "false",
"process.env.RUN_CONFIG": JSON.stringify(appConfig),
}),
new CopyWebpackPlugin({
patterns: [
{ from: 'public', to: 'public' },
]
}),
],
};

Related

How to make Webpack-dev-server work with react-router inside Vagrant?

I am working on a React / Typescript project using Webpack (v.4.44.2), along with Vagrant. For routing purposes, I tried to implement a BrowserHistory from react-router-dom. As you can imagine, http://localhost:8000/myUrl didn't work properly on refresh / manual entry at this point. After a bit of research, I tried without success to setup devServer.historyApiFallback and output.publicPath, but nothing works.
My webpack setup looks like this :
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
entry: './src/index.tsx',
target: 'web',
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist'),
publicPath: '/'
},
resolve: {
extensions: ['.tsx', '.ts', '.js'] // `.js` for external libs (/node_modules/)
},
module: {
rules: [
{ test: /\.tsx?$/i, use: 'ts-loader', exclude: /node_modules/ },
{ test: /\.tsx?$/i, use: 'prettier-loader', enforce: 'pre', exclude: /node_modules/ },
{ test: /\.css?$/i, use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader'], exclude: /node_modules/ },
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'src', 'index.html') }),
new MiniCssExtractPlugin({ filename: 'main.css' })
],
devServer: {
compress: true,
historyApiFallback: {
index: path.join(__dirname, 'dist'),
// index: '/',
},
// historyApiFallback: true,
host: '0.0.0.0',
public: '10.10.10.61',
port: 8000,
watchOptions: {
poll: true
}
}
};
As you can see, I tried several values for historyApiFallback, but I feel like I'm missing something, as I still have the 404 error on refresh. As I'm inside a Vagrant, I wonder if it's an issue regarding the fact that dev bundles are not written to the disk ? or maybe something related to the Vagrant network setup ?
My Vagrantfile is as follows:
Vagrant.configure(2) do |config|
# see https://webpack.js.org/guides/development-vagrant/
config.vm.network :private_network, ip: "10.10.10.61"
config.ssh.insert_key = false
config.vm.define "dev", primary: true do |app|
app.vm.provider "docker" do |d|
d.image = "someImage"
d.name = "#{PROJECT}_dev"
d.has_ssh = true
d.ports = ["0.0.0.0:8000:8000"]
d.env = DOCKER_ENV
end
[...]
end
end
Do you have any idea?
The problem is solved as follow
Vagrant setup :
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
entry: './src/index.tsx',
target: 'web',
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist'),
publicPath: '/'
},
resolve: {
extensions: ['.tsx', '.ts', '.js'] // `.js` for external libs (/node_modules/)
},
module: {
rules: [
{ test: /\.tsx?$/i, use: 'ts-loader', exclude: /node_modules/ },
{ test: /\.tsx?$/i, use: 'prettier-loader', enforce: 'pre', exclude: /node_modules/ },
{ test: /\.css?$/i, use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader'], exclude: /node_modules/ },
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src', 'index.html'),
filename: path.resolve(__dirname, 'dist', 'index.html')
}),
new MiniCssExtractPlugin({ filename: 'main.css' })
],
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
publicPath: '/',
compress: true,
historyApiFallback: {
disableDotRule: true, // this was what messed me up : in my URL, I have IDs, which for some reason contains dots
index: '/', // same as output.publicPath
},
host: '0.0.0.0',
public: '10.10.10.61',
port: 8000,
watchContentBase: true,
watchOptions: {
poll: true
}
}
};
No tricky stuff related to the filesystem or vagrant. Just an URL "dot" issue that I didn't notice -__-"

How can I track reactjs error on console when using webpack?

I am using react with web pack but I am not able to track react error on console.
I have installed "npm-watch" and it works fine whenever I am doing any changes but I am not able to track react error on console.
Here is my webpack.config.js file
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test:/\.css$/,
use:['style-loader','css-loader']
},
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 80000, // Convert images < 8kb to base64 strings
name: 'src/[name].[ext]'
}
}]
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new HtmlWebPackPlugin({
template: "./public/index.html",
filename: "./index.html",
favicon: './public/favicon.ico'
})
],
devServer: {
contentBase: './dist'
},
watchOptions: {
poll: true,
ignored: /node_modules/
}
};

[Webpack][React] On SSR with code-splitting how I can get the list of chunks needed by the page?

I've a React application with perfectly working SSR and Webpack code-splitting.
My webpack.config.js looks like this:
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ServerMiniCssExtractPlugin = require("./server/utils/serverMiniCssExtractPlugin");
module.exports = [{
name: 'react-app',
mode: 'development',
devtool: 'eval',
cache: true,
entry: {
main: [
'babel-polyfill',
'webpack-hot-middleware/client',
'./react/index.tsx',
],
},
output: {
path: `${__dirname}/dist/__build__`,
filename: '[name].js',
chunkFilename: '[name].js',
publicPath: '/__build__/',
},
module: {
rules: [{
test: /\.(ts|js)x?$/,
loader: 'babel-loader',
exclude: [/node_modules/],
}, {
test: /\.scss$/,
oneOf: [{
resourceQuery: /^\?raw$/,
use: [MiniCssExtractPlugin.loader, {
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
camelCase: false,
localIdentName: '[local]',
},
}, 'sass-loader', 'postcss-loader'],
}, {
use: [MiniCssExtractPlugin.loader, {
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
camelCase: true,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
},
}, 'sass-loader', 'postcss-loader'],
}]
}],
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.DefinePlugin({
'process.env': {
CLIENT: JSON.stringify(true),
},
}),
new webpack.IgnorePlugin(/^vertx$/),
new MiniCssExtractPlugin({
filename: "style.css",
chunkFilename: "style.chunk.[id].css"
}),
],
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
test: /node_modules/,
name: 'vendor',
enforce: true
},
},
},
},
}, {
name: 'server-side rendering',
mode: 'development',
devtool: 'eval',
cache: true,
entry: [
'./react/ssr.tsx',
],
target: 'node',
output: {
path: `${__dirname}/dist/__server__/`,
filename: 'ssr.js',
publicPath: '/__server__/',
libraryTarget: 'commonjs2',
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
module: {
rules: [{
test: /\.(ts|js)x?$/,
exclude: [/node_modules/, /.+\.config.js/],
loader: 'babel-loader',
}, {
test: /\.scss$/,
oneOf: [{
resourceQuery: /^\?raw$/,
use: [ServerMiniCssExtractPlugin.loader, {
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
camelCase: false,
localIdentName: '[local]',
},
}, 'sass-loader', 'postcss-loader'],
}, {
use: [ServerMiniCssExtractPlugin.loader, {
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
camelCase: true,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
},
}, 'sass-loader', 'postcss-loader'],
}]
}],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.DefinePlugin({
'process.env': {
SERVER: JSON.stringify(true),
},
}),
new webpack.IgnorePlugin(/^vertx$/),
new ServerMiniCssExtractPlugin({
filename: "style.css",
chunkFilename: "style.chunk.[id].css"
}),
],
}];
... and it generates chunks for both js and css that using the app are loaded correctly when moving from the different pages, all mapped with react-router.
The problem is that when I reload one of the pages the needed css chunks are loaded once rendered and not linked directly in the page from the SSR, so for a second I have FOUC.
Since I would like using React-Helmet to inject in the page head the needed css chunks when I SSR the app how I can get in the code the list of chunks file names that are needed for the page that I reload?
Let say that the page needs:
0.js
2.js
style.chunk.0.css
style.chunk.2.css
How I can get the list of these files so I can generate dynamically the links in the page head?
Thanks.
Use the webpack-manifest-plugin to generate a manifest.json file that will include a list of all your chunks.
In your webpack.config.js:
var ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
// ...
plugins: [
new ManifestPlugin()
]
};
This will generate a manifest.json file in your root output directory with a mapping of all source file names to their corresponding output file, for example:
{
"mods/alpha.js": "mods/alpha.1234567890.js",
"mods/omega.js": "mods/omega.0987654321.js"
}

Webpack hot module replacement stuck at [HMR] Waiting for update signal from WDS

I'm using webpack hot module replacement in my react project.
configuration looks like below.
let compilerConfig = {
entry: [
'babel-polyfill',
'webpack-dev-server/client?http://0.0.0.0:9000/',
'webpack/hot/only-dev-server',
path.join(ws.srcDir, 'client', 'src', 'index.js'),
],
devtool: 'source-map',
output: {
path: path.resolve(ws.srcDir, 'public'),
filename: 'main.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.(?:p|s)?css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
{
loader: 'postcss-loader',
options: { config: { path: path.join(__dirname, "postcss.config.js") } }
},
],
}),
},
{
test: /\.(png|woff|woff2|eot|ttf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
},
{
test: /\.(js|jsx)?$/,
include: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'node_modules', 'astro'),
],
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
'react',
'es2015',
'stage-2'
]
},
},
{
test: /\.svg$/i,
use: [
{
loader: "babel-loader",
},
{
loader: "svg-react-loader",
query: {
classIdPrefix: '[name]-[hash:8]__',
propsMap: {
fillRule: 'fill-rule',
foo: 'bar'
},
xmlnsTest: /^xmlns.*$/
}
}
],
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': `"${NODE_ENV}"`,
}),
new ExtractTextPlugin('styles.css'),
new HTMLWebpackPlugin({
template: path.join(ws.srcDir, 'client', 'src', "index.html"),
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
};
const serverConfig = {
contentBase: path.resolve(ws.srcDir, 'client', 'src'),
port: process.env.PORT || '9000',
inline: true,
host: '0.0.0.0',
historyApiFallback: true,
stats: {
colors: true,
},
headers: {
'Access-Control-Allow-Origin': '*'
},
};
And i'm starting webpack dev server through gulp as below.
gulp.task('webpack-dev', function() {
WebpackDevServer.addDevServerEntrypoints(compilerConfig, serverConfig);
const webpackConf = webpack(compilerConfig);
new WebpackDevServer(webpackConf, serverConfig)
.listen('9000', '0.0.0.0', function(err) {
if (err)
throw new Error("webpack-dev-server", err);
// Server listening
console.info("[webpack-dev-server]", "http://localhost:9000");
})
})
Getting [WDS] Disconnected! error after some time. And also i'm not seeing [WDS] Hot Module Replacement enabled. log in the console.
when i do a code change webpack is recompiling, but don't see it reflecting in the browser.
Using below version.
webpack = 2.3.x
webpack-dev-server = 2.4.x
Found the problem. I was loading a script in my index.html. That got failed(404). This is causing Hot Module Replacement to fail.

Enable source maps in Webpack

I have a problems with souce maps. They are generated but apparently not used.
I use webpack-dev-server, react hot module replacement and Webpack v3.x if that is important.
Inside of my webpack-config i use devtool: 'source-map' and I run my script like this:
"webpack": "cross-env NODE_ENV=development webpack-dev-server -d --config webpack.config.js"
Example of error that I get
When I click on this client?e36c:157 it doesn't take me to source code but:
If I remove devtools from webpack.config and -d tag from script I get the same output
**webpack.config.js**
const path = require('path')
const webpack = require('webpack')
const publicPath = path.resolve(__dirname, './src/client')
const buildPath = path.resolve(__dirname, './src')
// const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
const Write = require('write-file-webpack-plugin')
process.noDeprecation = true
module.exports = {
devtool: 'source-map',
performance: {
hints: false,
},
devServer: {
hot: true,
port: 3001,
host: 'localhost',
/* Needed only if using Browsersync */
headers: { 'Access-Control-Allow-Origin': '*', },
proxy: {
'**': {
target: 'http://localhost:3000',
secure: false,
changeOrigin: true,
},
},
},
context: publicPath,
entry: {
bundle: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3001',
'webpack/hot/only-dev-server',
'script-loader!jquery/dist/jquery.min.js',
'script-loader!tether/dist/js/tether.min.js',
'script-loader!bootstrap/dist/js/bootstrap.min.js',
'./app.js',
],
},
output: {
path: path.join(buildPath, 'dist'),
filename: '[name].js',
publicPath: 'http://localhost:3001/',
},
resolve: {
extensions: [ '.js', '.jsx', ],
alias: {
// Container
Container: path.resolve(__dirname, 'src/client/scenes/Container.jsx'),
// Components
FormComponent: path.resolve(
__dirname,
'src/client/scenes/feature/components/FormComponent.jsx'
),
Feature: path.resolve(__dirname, 'src/client/scenes/feature/Feature.jsx'),
TitleComponent: path.resolve(
__dirname,
'src/client/scenes/home/components/TitleComponent.jsx'
),
Home: path.resolve(__dirname, 'src/client/scenes/home/Home.jsx'),
Navigation: path.resolve(__dirname, 'src/client/scenes/shared/navigation/Navigation.jsx'),
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules|dist|build/,
loader: 'babel-loader',
options: {
babelrc: true,
},
},
{
test: /\.local\.(css|scss)$/,
use: [
'style-loader',
'css-loader?sourceMap&modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
'postcss-loader?sourceMap',
'sass-loader?sourceMap',
{
loader: 'sass-resources-loader',
options: {
resources: [
path.resolve(__dirname, './src/client/styles/scss/variables.scss'),
],
},
},
],
},
{
test: /^((?!\.local).)+\.(css|scss)$/,
use: [
'style-loader',
'css-loader?sourceMap',
'postcss-loader?sourceMap',
'sass-loader?sourceMap',
],
},
{
test: /\.(gif|png|jpg)$/,
/* We can specify custom publicPath if needed */
loader: 'url-loader',
},
],
},
plugins: [
new Write(),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
jquery: 'jquery',
}),
],
}

Resources