Using webpack-dev-server and I want to put index.html in the root folder - webpack-dev-server

This is my current webpack.config.js:
module.exports = {
// ...
mode: 'development',
devtool: 'inline-source-map',
devServer: {
static: {
directory: path.join(__dirname, 'dist'),
},
compress: true,
port: 9000,
historyApiFallback: {
index: 'index.html'
},
},
// ...
};
I can make it work if the index.html file is in the dist folder but I don't want it there because I want that folder to be purely generated files so that I can tell git to ignore it.
How can I make the dev server run from using an index.html in the root folder (or even from ./src for that matter).

Related

Hot reloading for webpack-dev-server is not working when the nested directory structure is passed as output and contentBase parameter

I got the webpack-dev-server hot reloading feature working with the following webpack.config.js file.
mode: 'development',
watch: true,
entry: path.join(__dirname, 'src/app.js'),
devServer: {
contentBase: path.join(__dirname, 'public'),
hot: true,
inline: true,
historyApiFallback: true,
watchContentBase: true,
port: 9001
},
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
},
Index.html serves to
<script src="./bundle.js"></script>
What i am trying to do right now is refactor the directories so that the bundle.js will fall into public/build and index.html will fall into public/dist. So i changed my webpack.config.js as following
mode: 'development',
watch: true,
entry: path.join(__dirname, 'src/app.js'),
devServer: {
contentBase: path.join(__dirname, 'public', 'dist'),
hot: true,
inline: true,
historyApiFallback: true,
watchContentBase: true,
port: 9001
},
output: {
path: path.join(__dirname, 'public','build'),
filename: 'bundle.js',
},
Index.html serves to
<script src="../build/bundle.js"></script>
But the above config does not work and i get bundle.js config not found.
My express server is serving the static path as follows.
const publicPath=path.join(__dirname,'..','public')
console.log('publicpath',publicPath);
app.use(express.static(publicPath))
Any reason why the directory structure fail to work with HMR?
Attached is my directory structure.

Entrypoint undefined, Content not from webpack. What wrong in my config?

I set entry point and output in webpack.config.js but I get some errors:
i 「wds」: Project is running at http://localhost:9000/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from D:\Projects\react-redux-registration-login-example\public
i 「wds」: 404s will fallback to /index.html
i 「wdm」: Hash: cb37c515d6a1771b5bcb
webpack.config.js and every file and folder in config file is existing
// Webpack uses this to work with directories
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
// This is main configuration object.
// Here you write different options and tell Webpack what to do
module.exports = {
// Path to your entry point. From this file Webpack will begin his work
entry: "./src/index.js",
// Path and filename of your result bundle.
// Webpack will bundle all JavaScript into this file
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js",
publicPath: '/'
},
module: {
rules: [
{
loader: "babel-loader",
test: /\.js$|jsx/,
exclude: /node_modules/
},
{ test: /\.html$/i, loader: 'html-loader' },
]
},
// Default mode for Webpack is production.
// Depending on mode Webpack will apply different things
// on final bundle. For now we don't need production's JavaScript
// minifying and other thing so let's set mode to development
mode: "development",
devServer: {
contentBase: path.join(__dirname, "public"),
inline: true,
compress: true,
port: 9000,
historyApiFallback: true
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
fileName: path.join('.', 'build', 'index.html')
})
]
};
I try to search some solution but it still doesnt work. Please help me find what wrong in my config.

Remove server from react-boilerplate

How should one do to remove server folder from react-boilerplate? Question is also asked here by another person https://github.com/react-boilerplate/react-boilerplate/issues/2110.
Removing just server folder will not work because the webpack dev configuration is utilising it for hot reload as well as your npm start command starts express server from this folder.
If you want to remove server folder completely and still want the application to be working as it was like hot reloading etc, follow the below steps. We will require webpack dev server in that case:
Remove ./server folder manually.
Install webpack-dev-server and react-hot-loader as dev dependencies.
In your ./internals/webpack/webpack.dev.babel.js, do the following modifications:
Change entry to this:
entry: [
require.resolve('react-app-polyfill/ie11'),
'react-hot-loader/patch',
`webpack-dev-server/client?http://localhost:3000/`,
'webpack/hot/only-dev-server',
path.join(process.cwd(), 'app/app.js'), // Start with js/app.js
],
Add publicPath in output:
output: {
filename: '[name].js',
chunkFilename: '[name].chunk.js',
publicPath: `http://localhost:3000/`,
},
Add webpack dev server config property in the same file:
devServer: {
port: 3000,
publicPath: `http://localhost:3000/`,
compress: true,
noInfo: false,
stats: 'errors-only',
inline: true,
lazy: false,
hot: true,
open: true,
overlay: true,
headers: { 'Access-Control-Allow-Origin': '*' },
contentBase: path.join(__dirname, '..', '..', 'app', 'build'),
watchOptions: {
aggregateTimeout: 300,
ignored: /node_modules/,
poll: 100,
},
historyApiFallback: {
verbose: true,
disableDotRule: false,
},
},
In ./internals/webpack/webpack.base.babel.js, add the line:
devServer: options.devServer,
And finally, modify your start script in package.json as below:
"start": "cross-env NODE_ENV=development node --trace-warnings ./node_modules/webpack-dev-server/bin/webpack-dev-server --color --config internals/webpack/webpack.dev.babel.js",
And you are good to go!!
Just remove with rm -rf ./server if you feel harassed :)

Webpack dev server React Content Security Policy error

I have my single page app running on webpack-dev-server. I can load and reload my entry route over at localhost:8080 and it works every time. However i can load localhost:8080/accounts/login only via a link from within the app i.e whenever i reload localhost:8080/accounts/login from the browser refresh button i get
Cannot GET /accounts/login/
as the server response, and on the console i get
Content Security Policy: The page’s settings blocked the loading of a
resource at self (“default-src http://localhost:8080”). Source:
;(function installGlobalHook(window) { ....
This is my CSP header on the single page app's index.html
<meta http-equiv="Content-Security-Policy"
content="default-src * 'self' 'unsafe-inline' 'unsafe-eval'">
I am also not using any devtool on my webpack.config.json. What am i missing.
If you use Webpack in your project, please add output.publicPath = '/' and devServer.historyApiFallback = true in your webpack config file.
More info: React-router urls don't work when refreshing or writting manually
I struggled a couple hours to fix this issue. There is a just simple code that you have to add. Just follow the instruction of below. If you face problem to browse from specific url to another url, you will be able to fix that also. If you would like to configure from webpack config file, then write below's code.
devServer: {
historyApiFallback: true
}
And If you would like to run by cli command, then use the below's code.
"start": "webpack-dev-server --history-api-fallback"
It worked for me. I had not to do anything else to fix this issue like meta tag or something else.
If you're using Rails and Webpacker and get this error, note that the initializer config/initializers/content_security_policy.rb has a Content Security Policy for Rails.env.development. Changing :https to :http on that line solved the error for me. (And remember that localhost is not the same as 127.0.0.1 as far as the CSP is concerned.)
adding output: { ..., publicPath: "/", } and devServer: { historyApiFallback: true } worked
in webpack.config.js
const path = require("path");
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "public"),
filename: "main.js",
publicPath: "/", // ++
},
target: "web",
devServer: {
port: "6060",
static: ["./public"],
open: true,
hot: true,
liveReload: true,
historyApiFallback: true, // ++
},
resolve: {
extensions: [".js", ".jsx", ".json", ".ts"],
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: "babel-loader",
},
// CSS rules
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};
I had similar issue. Had to remove the contentBase line from devServer configuration in webpack.config.js.
This is my webpack.config.js:
var path = require("path");
module.exports = {
devtool: 'inline-source-map',
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
publicPath: "/assets/",
filename: "bundle.js"
},
devServer: {
port: 9002
},
module: {
rules: [
{ test: /\.js$/, use: 'babel-loader' }
]
}
};

Webpack server configuration + external libs

I have the following webpack configuration file:
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const LiveReloadPlugin = require('webpack-livereload-plugin');
const path = require('path');
module.exports = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:2000', // WebpackDevServer host and port
'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
'./app/index.tsx'
],
output: {
path: __dirname + '/dist/',
filename: 'bundle.js'
},
devtool: 'source-map',
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
},
module: {
loaders: [
{
test: /\.tsx?$/,
loaders: ['react-hot', 'ts'],
include: path.join(__dirname, 'app')
}
],
preLoaders: [
'source-map-loader'.
{test: /\.js$/, loader: 'source-map-loader'}
]
},
plugins: [
new CopyWebpackPlugin([
{from: './app/index.html', to: './dist/index.html'}
]),
new webpack.HotModuleReplacementPlugin()
],
builds.
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
}
};
and here is my server configuration:
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
contentBase: './dist',
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
open: 'http://localhost:2000'
}).listen(2000, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:2000/');
});
I want to be able to access the application from root path: http://localhost:2000 and not http://localhost:2000/dist.
One more thing, is there any way to move all the external dependancies from node_modules to dist with webpack (without the need to include the script tag in the index.html file)?
First of all for set application start point you need to set publicPath to "/" or publicPath: 'http://localhost:2000'
Your second question
Is there any way to move all the external dependancies from node_modules to dist with webpack?
Yes
You can use different file just for external modules and bundle that file. You don't need to take care of index.html file let webpack plugin HtmlWebpackPlugin take care of it.
First step set entry points for your app
entry: {
'vendors': './src/vendors.ts',//your external libraries
'app': './src/main.ts' //your app
}
and out put
output: {
publicPath: '/',
filename: '[name].js'//this will generate two different files app.js, vendor.js
}
How to add HtmlWebpackPlugin?
Add this in you plugins
new HtmlWebpackPlugin({
template: "./src/index.html",
minify:false
})
Now it will place script tags for you
on you server configuration change your public path to
publicPath: '/',

Resources