Enable source maps in Webpack - reactjs

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',
}),
],
}

Related

Webpack React Default URL

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' },
]
}),
],
};

Webpack 5: Is it possible to output a javascript file non-bundled for configuration

I have a React TypeScript project that uses webpack 5.
I am trying to get a runtime-config.js file that I can change out in production by importing it as decribed in a similar Vuejs Docker issue.
I wanted to use File Loader but found that it's been deprecated in webpack 5
Here's what I want to achieve:
have ./runtime-config.js non bundled so that I can refer to it on the window object
easily reference that file in React (TypeScript) so that this dynamic configuration can be read.
Any help is appreciated.
Below is my webpack configuration:
// webpack.config.js
import path from 'path'
import { Configuration as WebpackConfiguration, DefinePlugin, NormalModuleReplacementPlugin } from 'webpack'
import { Configuration as WebpackDevServerConfiguration } from 'webpack-dev-server';
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import ESLintPlugin from 'eslint-webpack-plugin'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
const CopyPlugin = require('copy-webpack-plugin');
interface Configuration extends WebpackConfiguration {
devServer?: WebpackDevServerConfiguration;
}
const config: Configuration = {
mode: 'development',
target: 'web',
devServer: {
static: path.join(__dirname, 'build'),
historyApiFallback: true,
port: 4000,
open: true,
liveReload: true,
},
output: {
publicPath: '/',
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js',
},
entry: {
main: './src/index.tsx',
'pdf.worker': path.join(__dirname, '../node_modules/pdfjs-dist/build/pdf.worker.js'),
},
module: {
rules: [
{
test: /\.(ts|js)x?$/i,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript',
],
},
},
},
{
test: /\.(sa|sc|c)ss$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
{
loader: 'postcss-loader', // postcss loader needed for tailwindcss
options: {
postcssOptions: {
ident: 'postcss',
plugins: [tailwindcss, autoprefixer],
},
},
},
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
outputPath: '../fonts',
},
},
{
test: /runtime-config.js$/,
use: [
{
loader: 'file-loader',
options: {
name: 'runtime-config.js',
},
},
],
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new NormalModuleReplacementPlugin(
/^pdfjs-dist$/,
(resource) => {
// eslint-disable-next-line no-param-reassign
resource.request = path.join(__dirname, '../node_modules/pdfjs-dist/webpack.js')
},
),
new CopyPlugin({
patterns: [
// relative path is from src
{ from: 'public/images', to: 'images' },
],
}),
// Add type checking on dev run
new ForkTsCheckerWebpackPlugin({
async: false,
}),
// Environment Variable for Build Number - Done in NPM scripts
new DefinePlugin({
VERSION_NUMBER: JSON.stringify(process.env.VERSION_NUMBER || 'development'),
}),
// Add lint checking on dev run
new ESLintPlugin({
extensions: ['js', 'jsx', 'ts', 'tsx'],
}),
],
devtool: 'inline-source-map',
};
export default config

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 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.

Hot reloald webpac-dev-server when changing sass

i have simple webpack build with webpack-dev-server. It's work, and when i changing .js file its autorefreshingin browser. But when i changhing .sass nothing happens. Here is my webpack.confing
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/sass/main.sass',
],
output: {
filename: 'bundle.js',
path: resolve(__dirname, 'dist'),
publicPath: '/',
},
context: resolve(__dirname, 'app'),
devServer: {
hot: true,
contentBase: resolve(__dirname, 'dist'),
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
loaders: [
'babel-loader',
],
exclude: /node_modules/,
},
{
test: /\.sass$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'sass-loader',
query: {
sourceMap: false,
},
},
],
}),
},
{ test: /\.(png|jpg)$/, use: 'url-loader?limit=15000' },
{ test: /\.eot(\?v=\d+.\d+.\d+)?$/, use: 'file-loader' },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
{ test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml' },
]
},
plugins: [
new ExtractTextPlugin({ filename: 'style.css', disable: false, allChunks: true }),
new CopyWebpackPlugin([{ from: 'vendors', to: 'vendors' }]),
new OpenBrowserPlugin({ url: 'http://localhost:8080' }),
new webpack.HotModuleReplacementPlugin(),
],
};
module.exports = config;
Also, please tell me how to make the files get in the right folders during the build (.css to dist/css, js to dist/js), 'cuz rigth now they all go to the root of dest folder.
Hot reloading doesn't work with extract-text-webpack-plugin. You should not use it in development and you can easily disable it by setting the disable option to true in development. You can use an environment variable like so:
new ExtractTextPlugin({
filename: 'style.css',
disable: process.env.NODE_ENV !== 'production',
allChunks: true
}),
This will only extract the CSS in production mode, so you'd need to run your production build with:
NODE_ENV=production webpack [options]
Or if you are on windows:
set NODE_ENV=production && webpack [options]
There is also cross-env if you look for a cross platform solution.
For getting the JavaScript files to dist/js and the CSS file to dist/css you could set output.path to dist/js and then tell extract-text-webpack-plugin to generate the file into ../css/style.css.
output: {
filename: 'bundle.js',
path: resolve(__dirname, 'dist/js'),
publicPath: '/',
},
plugins: [
new ExtractTextPlugin({
filename: '../css/style.css',
disable: process.env.NODE_ENV !== 'production',
allChunks: true
}),
// other plugins
]

Resources