bundle.js not found with webpack dev server - reactjs

I'm having an issue with React/Redux/Webpack/Router.
Any "sub pages", such as: "/home/test", "users/registration" etc... fail to be loaded - and I get errors loading the "bundle.js" file generated by webpack.
The reason seems to be that the request to fetch the "bundle.js" is with the following url:
for path "/home/test": "/home/bundle.js"
for path "/users/registration": "/users/bundle.js"
Same issue occurs with the loading of "css" files and other resources.
This is my webpack configuration:
const { resolve } = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const config = {
devtool: 'cheap-module-eval-source-map',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./main.js',
//'./assets/scss/main.scss',
],
output: {
filename: 'bundle.js',
path: resolve(__dirname, 'dist'),
publicPath: '/',
},
context: resolve(__dirname, 'src'),
devServer: {
hot: true,
contentBase: resolve(__dirname, 'build'),
publicPath: '/',
historyApiFallback: true
},
module: {
rules: [
/* {
enforce: "pre",
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "eslint-loader"
}, */
{
test: /\.(js|jsx)$/,
loaders: [
'babel-loader',
],
exclude: /node_modules/,
},
{
test: /\.(scss|sass)$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'sass-loader',
query: {
sourceMap: false,
},
},
],
publicPath: '../'
}),
},
{ test: /\.(png|jpg|gif)$/, use: 'url-loader?limit=15000&name=images/[name].[ext]' },
{ test: /\.eot(\?v=\d+.\d+.\d+)?$/, use: 'file-loader?&name=fonts/[name].[ext]' },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff&name=fonts/[name].[ext]' },
{ test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream&name=fonts/[name].[ext]' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml&name=images/[name].[ext]' },
]
},
plugins: [
new webpack.LoaderOptionsPlugin({
test: /\.js$/,
options: {
eslint: {
configFile: resolve(__dirname, '.eslintrc'),
cache: false,
}
},
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new ExtractTextPlugin({ filename: './styles/style.css', disable: true, allChunks: true }),
new CopyWebpackPlugin([{ from: 'vendors', to: 'vendors' }]),
new OpenBrowserPlugin({ url: 'http://localhost:8080' }),
new webpack.HotModuleReplacementPlugin(),
],
};
module.exports = config;
It seems as if it always uses "../bundle.js" to find it for some reason.
Any help would be appreciated :)
Thank you,

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 -__-"

Webpack Dev Server (Uncaught SyntaxError: Unexpected token '<' )

Building TS/SASS with Webpack works fine, running this through VSCode Live Server plugin renders the index.html perfectly to the app folder.
Running webpack-dev-server with it looking at the same app folder does not. The page opens but there is a Javascript error Uncaught SyntaxError: Unexpected token '<'
And the page does not render the JS/CSS.
webpack.config.js
// Imports
var path = require("path");
// Plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Exports
module.exports = {
mode: 'development',
entry: './src/main.ts',
devtool: "inline-source-map",
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
output: {
filename: 'main.min.js',
path: path.resolve(__dirname, 'app')
},
devServer: {
open: 'http://localhost',
port: 80,
publicPath: path.resolve(__dirname, 'app'),
hot: true
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true }
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader"
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
]
}
tsconfig.json
{
"compilerOptions": {
"sourceMap": true
}
}
main.ts
console.log('Main.ts has loaded')
import './styles/main.scss'
Any help with this would be appreciated, I'm losing my mind lol.
My issue was with syntax in the webpack.config.js file.
I was neglecting to insert a comma at the end of the last entry in every object and array, believing it not to be necessary.
Here is a working config:
// Imports
var path = require("path");
// Plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Exports
module.exports = {
mode: 'development',
entry: './src/main.ts',
devtool: "inline-source-map",
output: {
filename: 'main.min.js',
path: path.resolve(__dirname, 'app'),
},
devServer: {
open: 'http://localhost',
port: 80,
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true },
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
]
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader",
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css",
}),
]
}

Webpack 3.0: How can I exclude node_modules from build?

I tried to add 'target:node' to the webpack.dev.js to exclude node_modules from my bundle file. This results in an error. Now I have 'target:web' but has the node_modules back in. This is my config file for the applicationpart(trying to use DllReferencePlugin):
var path = require("path");
var webpack = require("webpack");
module.exports = {
target:'web',
devServer: {
contentBase: path.join(__dirname, "build"),
compress: true,
port: 9000
},
node: {
fs: 'empty'
},
cache: true,
devtool: "eval", //or cheap-module-eval-source-map
entry: {
app: path.join(__dirname, "client/app", "app.js")
},
output: {
path: path.join(__dirname, "buildf"),
filename: "ha.js",
chunkFilename: "[name].js"
},
plugins: [
//Typically you'd have plenty of other plugins here as well
new webpack.DllReferencePlugin({
context: path.join(__dirname, "client"),
manifest: require("./build/vendor-manifest.json")
}),
],
module: {
loaders: [
{
test: /\.js?$/,
loader: "babel-loader",
include: [
path.join(__dirname, "client") //important for performance!
],
exclude: [
path.resolve(__dirname, "node_modules")
],
query: {
cacheDirectory: true, //important for performance
plugins: ["transform-regenerator"],
presets: ["es2015", "stage-0"]
}
},
{ test: /\.(scss|sass)$/, loader: ['style-loader', 'css-loader', 'sass-loader'] },
{ test: /\.html$/, loader: 'raw-loader' },
{ test: /\.css$/, loader: 'css-loader' }
]
}
};
How can I exclude the node_modules folder from the ha.js (app bundle) build? for the complete code see here
Here an example:
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/, // <---
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]

Webpack 2 with historyApiFallback Not Working

I keep getting Cannot GET /task I tried to modify my webpack with solutions I found here but I still get it.
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app.js',
output: {
path: __dirname + '/dist',
filename: 'app.bundle.js'
},
module: {
rules: [
{
test: /\.s?css$/,
use: ['style-loader', 'css-loader', 'sass-loader']
}, {
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
}, {
test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader?name=fonts/[name].[ext]'
}
]
},
devServer: {
historyApiFallback: {
index: '/index.html'
},
stats: true,
inline: true,
progress: true
}
plugins: [new HtmlWebpackPlugin({template: './src/index.html'})]
}
I think client gets index.html only when path is /.
Try to use this setting.
devServer: {
historyApiFallback: true
}

Code Splitting ~ ReferenceError: System is not defined

My code hit the error
ReferenceError: System is not defined
In line
<IndexRoute getComponent={(nextState, cb) => System.import('./containers/Home').then(module => cb(null, module))} />
How do I define System. Is it related to my webpack settings? Here how I put it
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var stylus = require('stylus');
module.exports = {
debug: true,
devtool: 'eval',
entry: {
"vendor": ["react", "react-router", 'react-dom'],
"app": ['webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './app/App.js']
},
output: {
pathinfo: true,
path: path.resolve(__dirname, 'public'),
filename: '[name].js',
publicPath: 'http://localhost:3000/'
},
plugins: [
new HtmlWebpackPlugin({
title: 'Welcome!',
template: './index_template.ejs',
inject: 'body'
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.UglifyJsPlugin({
output: {
comments: false
},
compress: {
warnings: false
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity,
filename: 'vendor.bundle.js'
})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loaders: ['react-hot', 'babel']
},
{
test: /\.styl$/,
exclude: /(node_modules|bower_components)/,
// loader: 'style!css?resolve url?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]__[hash:base64:5]!postcss!stylus-loader'
loader: 'style!css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]__[hash:base64:5]!postcss!stylus-loader'
},
{
test: /\.(png|jpg)$/,
exclude: /(node_modules|bower_components)/,
loader: 'url-loader?name=images/[name].[ext]&limit=8192'
},
{
test: /\.(ttf|otf|eot)$/,
exclude: /(node_modules|bower_components)/,
loader: 'url-loader?name=fonts/[name].[ext]&limit=8192'
},
{
test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
},
{
test: /\.scss$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass?resolve url'
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.js$/,
include: path.resolve('node_modules/mapbox-gl-shaders/index.js'),
loader: 'transform/cacheable?brfs'
}
]
},
resolve: {
root: path.join(__dirname, '..', 'app'),
alias: {
'react': path.join(__dirname, 'node_modules', 'react')
},
extensions: ['', '.js', '.jsx', '.json', '.css', '.styl', '.png', '.jpg', '.jpeg', '.gif']
},
stylus: {
'resolve url': true
},
postcss: function () {
return [autoprefixer];
}
};
(Disclaimer: I am new to React-Router and webpack, so this may be
obvious to someone with more familiarity)
Your webpack build stack probably doesn't have configured System.import. I suppose that you use webpack 1 and support of System.import will be only in webpack 2.
You can change your existing code to current popular code splitting solution:
<IndexRoute
getComponent={(nextState, cb) => {
require.ensure([], require => {
// default import is not supported in CommonJS standard
cb(null, require('./containers/Home').default)
});
}}
/>
Note that you must specify .default if you want to use default import in CommonJS standard.

Resources