Webpack outputs a minified but oversized JS file - javascript

I'm working with Webpack for JS minification. I'm importing 3 modules in one single minified bundle, but the final result is a huge file size for what is being imported (over 90kb) - they each look like this:
1:
var $ = require('jquery');
$(function() {
// main expansion element
$(".expander").click(function() {
var subShown = $(this).children(".indented").css("display");
if (subShown != "block") {
$(this).children(".indented").css("display", "block");
$(this).children(".caret").addClass("reversedCaret");
} else {
$(this).children(".indented").css("display", "none");
$(this).children(".caret").removeClass("reversedCaret");
}
});
// sub expansion element - .caret class is targeted as well due to issue with clicking on it not registering as a .sub-expander click
$(".sub-expander, .caret").click(function() {
var subSelectText = $(".sub-expander").text();
if (subSelectText != "More") {
$(".sub-expander").text("More");
} else {
$(".sub-expander").text("Show Less");
}
});
// stop propagation on the link element within .expander class
$(".indented").click(function(event) {
event.stopPropagation();
});
});
2:
console.log("a test message");
var clickButton = document.getElementById("clicker");
clickButton.addEventListener("click", (e) => {
e.target.classList.toggle("modified");
});
3:
class ColorPick extends React.Component {
constructor(props) {
super(props);
this.state = {
color: "Let's pick a color"
};
}
changeColor(event) {
var colorInput = document.getElementById('colorInput').value;
this.setState({
color: event.target.value,
backgroundColor: event.target.value
});
if (colorInput === '') {
this.setState({
color: "Let's pick a color",
backgroundColor: "#fff",
});
}
}
render () {
var styleObj = {
backgroundColor: this.state.backgroundColor,
};
return (
<section style={styleObj} id="Profile" >
<h2 className="colorHeader">{this.state.color}</h2>
<input id="colorInput" placeholder="Enter Hex Code Here" onChange={this.changeColor.bind(this)}/>
<div id="slider"></div>
</section>
);
}
}
ReactDOM.render(<ColorPick name="connorcolorpicker" />, document.getElementById('color-picker'));
These three files by themselves clock in at 12kb total. However in the webpack minified bundle it clocks out at 90kb. That doesn't make sense to me. My webpack config looks like this:
webpack.config.js:
var debug = false;
var path = require('path');
var webpack = require('webpack');
module.exports = {
context: __dirname,
// entry is already defined in gulpfile.js - leave this line commented out.
// entry: "/app/js/script.js",
devtool: debug ? "inline-sourcemap" : null,
module: {
rules: [{
test: /\.js$/,
use: 'babel-loader'
}],
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
query :{
presets:['react','es2015']
},
exclude: /node_modules/
}
]
},
resolve: {
root: [path.resolve(__dirname, 'app'), path.resolve(__dirname, 'node_modules')],
extensions: ['', '.js']
},
output: {
path: __dirname + "public/javascripts",
filename: "scripts.min.js"
},
plugins: debug ? [] : [
// new webpack.optimize.DedupePlugin(),
// new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ minimize: true, mangle: true })
],
};
[15:20:33] Version: webpack 1.15.0
Asset Size Chunks Chunk Names scripts.min.js 90.1 kB 0 [emitted] main
I was having issues with this in the past and the answers suggested to set debug to false. I did that but it isn't behaving as expected.
Why is 12kb worth of JS/imports totaling out to 90kb in Webpack?

Related

Webpack problem generating sourcemaps -- only generated when a particular plugin is disabled

I'm using my own custom plugin to strip some optional code from a build. This works well, but for some reason it seems to be blocking generation of source maps.
My best guess is that the fact that I'm modifying the index.js output file interferes with the ability to generate a map of for that file. If I comment out the plugin, my source maps come back.
Is there perhaps something I can do to change order of plugin execution that will fix this? Or perhaps a way to strip code from source file input streams (not from the files themselves) rather than from the generated output?
I've tried explicitly adding SourceMapDevToolPlugin to my plugins, but that didn't help.
Here's my webpack.config.cjs file:
const { Compilation, sources } = require('webpack');
const { resolve } = require('path');
module.exports = env => {
const esVersion = env?.esver === '5' ? 'es5' : 'es6';
const dir = env?.esver === '5' ? 'web5' : 'web';
const chromeVersion = env?.esver === '5' ? '23' : '51';
// noinspection JSUnresolvedVariable,JSUnresolvedFunction,JSUnresolvedFunction
return {
mode: env?.dev ? 'development' : 'production',
target: [esVersion, 'web'],
entry: {
index: './dist/index.js'
},
output: {
path: resolve(__dirname, 'dist/' + dir),
filename: `index.js`,
libraryTarget: 'umd',
library: 'tbTime'
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: { presets: [['#babel/preset-env', { targets: { chrome: chromeVersion } }]] }
},
resolve: { fullySpecified: false }
}
]
},
resolve: {
mainFields: ['esm2015', 'es2015', 'module', 'main', 'browser']
},
externals: { 'by-request': 'by-request' },
devtool: 'source-map',
plugins: [
new class OutputMonitor {
// noinspection JSUnusedGlobalSymbols
apply(compiler) {
compiler.hooks.thisCompilation.tap('OutputMonitor', (compilation) => {
compilation.hooks.processAssets.tap(
{ name: 'OutputMonitor', stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE },
() => {
const file = compilation.getAsset('index.js');
let contents = file.source.source();
// Strip out dynamic import() so it doesn't generate warnings.
contents = contents.replace(/return import\(.*?\/\* webpackIgnore: true \*\/.*?tseuqer-yb.*?\.join\(''\)\)/s, 'return null');
// Strip out large and large-alt timezone definitions from this build.
contents = contents.replace(/\/\* trim-file-start \*\/.*?\/\* trim-file-end \*\//sg, 'null');
compilation.updateAsset('index.js', new sources.RawSource(contents));
}
);
});
}
}()
]
};
};
Full project source can be found here: https://github.com/kshetline/tubular_time/tree/development
I think using RawSource would disable the source map. The right one for devtool is supposed to be SourceMapSource so the idea looks like following:
const file = compilation.getAsset('index.js');
const {devtool} = compiler.options;
let contents = file.source.source();
const {map} = file.source.sourceAndMap();
// your replace work
// ...
compilation.updateAsset(
'index.js',
devtool
// for devtool we have to pass map file but this the original one
// it would be wrong since you have already changed the content
? new sources.SourceMapSource(contents, 'index.js', map)
: new sources.RawSource(contents)
);

How do I exclude a directory from my webpack build with vue-cli-3 setup

I just spent 3 hours putting this line:
exclude: ['./src/assets/sass']
in 20 different places. Please tell me where this should go?
Here is my current setup for the css-loader (util.js):
'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
// exclude: ['./src/assets/sass'],
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
const output = []
const loaders = exports.cssLoaders(options)
for (const extension in loaders) {
const loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
exclude: ['./src/assets/sass'],
use: loader
})
}
return output
}
exports.createNotifierCallback = () => {
const notifier = require('node-notifier')
return (severity, errors) => {
if (severity !== 'error') return
const error = errors[0]
const filename = error.file && error.file.split('!').pop()
notifier.notify({
title: packageConfig.name,
message: severity + ': ' + error.name,
subtitle: filename || '',
icon: path.join(__dirname, 'logo.png')
})
}
}
Here is what my base webpack file looks like:
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: ['babel-polyfill','./src/main.js']
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src'),
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')],
},
// {
// test: /\.scss$/,
// exclude: ['./src/assets/sass']
// },
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
Here is the vue-webpack file:
'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap
module.exports = {
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),
cssSourceMap: sourceMapEnabled,
cacheBusting: config.dev.cacheBusting,
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
Presumably this line should go in one of these files unfortunately it is not preventing webpack from attempting to build it (and therefore failing to do so)
Turns out after much experimentation that if I removed this line from the first snippet:
scss: generateLoaders('sass'),
The reason seems to be that even though the files in this directory are never used in my project, the loader attempts to load them because of the file name, so by not having a loader it does not attempt that and no other errors are thrown since the file is not used.
Presumably if one wanted to keep the loader and exclude a specific directory then you would need to put in a condition on this section in the first snippet:
for (const extension in loaders) {
const loader = loaders[extension]
//enter your condition here, i.e. if(loader === something) then push an object
// with "exclude"
output.push({
test: new RegExp('\\.' + extension + '$'),
exclude: ['./src/assets/sass'],
use: loader
})
}

Gulp webpack load jquery only once

I've got two Gulp tasks in my gulpfile.js. It's used for a website.
The first one compiles with webpack the main js file, used on all pages of the site (mainly visuals), and combines it to a single file.
gulp.task('scripts', function(callback) {
let firstBuildReady = false;
function done(err, stats) {
firstBuildReady = true;
if (err) { // hard error, see https://webpack.github.io/docs/node.js-api.html#error-handling
return; // emit('error', err) in webpack-stream
}
gulplog[stats.hasErrors() ? 'error' : 'info'](stats.toString({
colors: true
}));
}
let options = {
output: {
publicPath: '/js/',
filename: isDevelopment ? '[name].js' : '[name]-[chunkhash:10].js'
},
watch: isDevelopment,
devtool: isDevelopment ? 'cheap-module-inline-source-map' : false,
module: {
loaders: [{
test: /\.js$/,
//include: path.join(__dirname, "app/src/scripts/modules"),
loader: 'babel-loader',
query: {
presets: ["env"]
}
}]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
]
};
if (!isDevelopment) {
options.plugins.push(new AssetsPlugin({
filename: 'scripts.json',
path: __dirname + '/app/manifest',
processOutput(assets) {
for (let key in assets) {
assets[key + '.js'] = assets[key].js.slice(options.output.publicPath.length);
delete assets[key];
}
return JSON.stringify(assets);
}
}));
}
return gulp.src(jsSRC)
.pipe(plumber({
errorHandler: notify.onError(err => ({
title: 'Scripts',
message: err.message
}))
}))
.pipe(named(function(file){
return 'app'
}))
.pipe(webpackStream(options, null, done))
.pipe(gulpIf(!isDevelopment, uglify()))
.pipe(gulp.dest(jsDIST))
.on('data', function() {
if (firstBuildReady) {
callback();
}
});
});
The second one compiles each js module as a single file - some js scripts, used on special pages. These scripts are included only there where needed.
gulp.task('webpack', function(callback) {
let firstBuildReady = false;
function done(err, stats) {
firstBuildReady = true;
if (err) {
return;
}
gulplog[stats.hasErrors() ? 'error' : 'info'](stats.toString({
colors: true
}));
}
let options = {
output: {
publicPath: '/js/',
filename: isDevelopment ? '[name].js' : '[name]-[chunkhash:10].js'
},
watch: isDevelopment,
devtool: isDevelopment ? 'cheap-module-inline-source-map' : false,
module: {
loaders: [{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ["env"]
}
}]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin()
]
};
if (!isDevelopment) {
options.plugins.push(new AssetsPlugin({
filename: 'webpack.json',
path: __dirname + '/app/manifest',
processOutput(assets) {
for (let key in assets) {
assets[key + '.js'] = assets[key].js.slice(options.output.publicPath.length);
delete assets[key];
}
return JSON.stringify(assets);
}
}));
}
return gulp.src('app/src/scripts/modules/*.js')
.pipe(plumber({
errorHandler: notify.onError(err => ({
title: 'Webpack',
message: err.message
}))
}))
.pipe(named())
.pipe(webpackStream(options, null, done))
.pipe(gulpIf(!isDevelopment, uglify()))
.pipe(gulp.dest(jsDIST))
.on('data', function() {
if (firstBuildReady) {
callback();
}
});
});
But I have to include Jquery in every single file for the second task, otherwise it's not compiled. But Jquery is included in the main app.js file.
How can I solve it?
Thanks
Since it sounds like you're using a somewhat exotic way of loading JS in your application (instead of approaches like require.ensure), your easiest option may be to use Webpack externals when building your individual modules. Your main script/page will have to ensure that jQuery is globally exposed (like under window.$ or window.jQuery). Then, for your webpack config, include something like this:
{
// ...
externals: {
jquery: '$'
}
}
This will substitute $ for all require('jquery') calls instead of including jquery in each JS bundle.

How to use Webpack and Gulp with multiple entry points to transpile app and test directories?

I am building a basic blog project to practice using React, ES6, and Mocha test framework. I'm having trouble transpiling my ES6 tests and app code within my default Gulp task.
I get this error when I run the default task and change the contents of ./test/posts.js for the watch to take effect:
[11:17:29] Using gulpfile ~/WebstormProjects/blog/gulpfile.js
[11:17:29] Starting 'default'...
[11:17:29] Finished 'default' after 8.54 ms
stream.js:75
throw er; // Unhandled stream error in pipe.
^
Error: invalid argument
at pathToArray (/Users/christian/WebstormProjects/blog/node_modules/memory-fs/lib/MemoryFileSystem.js:44:10)
at MemoryFileSystem.mkdirpSync (/Users/christian/WebstormProjects/blog/node_modules/memory-fs/lib/MemoryFileSystem.js:139:13)
at MemoryFileSystem.(anonymous function) [as mkdirp] (/Users/christian/WebstormProjects/blog/node_modules/memory-fs/lib/MemoryFileSystem.js:279:34)
at Compiler.<anonymous> (/Users/christian/WebstormProjects/blog/node_modules/webpack/lib/Compiler.js:229:25)
at Compiler.applyPluginsAsync (/Users/christian/WebstormProjects/blog/node_modules/tapable/lib/Tapable.js:60:69)
at Compiler.emitAssets (/Users/christian/WebstormProjects/blog/node_modules/webpack/lib/Compiler.js:226:7)
at Watching.<anonymous> (/Users/christian/WebstormProjects/blog/node_modules/webpack/lib/Compiler.js:54:18)
at /Users/christian/WebstormProjects/blog/node_modules/webpack/lib/Compiler.js:403:12
at Compiler.next (/Users/christian/WebstormProjects/blog/node_modules/tapable/lib/Tapable.js:67:11)
at Compiler.<anonymous> (/Users/christian/WebstormProjects/blog/node_modules/webpack/lib/CachePlugin.js:40:4)
Process finished with exit code 1
webpack.config.js
var path = require('path');
var babel = require('babel-loader');
module.exports = {
entry: {
app: './app/js/blog.js',
test: './test/posts.js'
},
output: {
filename: '[name].bundle.js',
path: './build',
sourceMapFilename: '[name].bundle.map'
},
watch: true,
devtool: '#sourcemap',
module: {
loaders: [
{
loader: 'babel',
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
query: {
presets: ['react', 'es2015']
}
}
],
resolve: {
root: path.resolve('./app'),
extensions: ['', '.js']
}
}
};
gulpfile.js
var gulp = require('gulp');
var webpack = require('webpack-stream');
var watch = require('gulp-watch');
var babel = require('babel-loader');
var named = require('vinyl-named');
gulp.task('default', function() {
watch(['./app/**/*.js', './test/*.js'], function() {
return gulp.src(['./app/js/blog.js', './test/posts.js'])
.pipe(named())
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./build'));
});
});
gulp.task('testBundle', function() {
gulp.src('./test/posts.js')
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./build'));
});
posts.js
import expect from 'expect'
import { post, posts, addPost } from '../app/js/blog'
import { createStore } from 'redux'
describe('Blog', () => {
describe('posts', () => {
it('should be able to create a post', () => {
let store = createStore(posts);
store.dispatch(addPost('First Post', 'Blah blah blah'))
let blah = { id: 'First Post', content: 'Blah blah blah'}
expect(store.getState()).toEqual(blah)
});
it('should be able to create multiple posts', () => {
let store2 = createStore(posts);
store2.dispatch(addPost('Second Post', 'Shh'))
let expectedState1 = { id: 'Second Post', content: 'Shh' }
expect(store2.getState()).toEqual(expectedState1)
store2.dispatch(addPost('Third Post', 'Whatever'))
let expectedState2 = { id: 'Third Post', content: 'Whatever'}
expect(store2.getState()).toEqual(expectedState2)
})
});
});
Ultimately, I'd like the transpiled code to be found at ./build/blog.bundle.js and ./build/posts.bundle.js for ./app/js/blog.js and ./test/posts.js, respectively.
There were some issues with my webpack.config.js and gulpfile.js. Apparently, the path property within the output object in webpack.config.js was conflicting with gulp.dest('./build'). I also reformatted some things in the config file to mirror a working one. Below is the code that should work. Hopefully this helps others trying to accomplish the same thing.
I have gulp starting webpack to produce separate bundle files for app and test entry points. I also get sourcemaps for each of the bundles that are created. Now I can write tests and app code in ES6 and run them with Mocha within WebStorm!
gulpfile.js
var gulp = require('gulp');
var webpack = require('webpack-stream');
var watch = require('gulp-watch');
gulp.task('default', function() {
watch(['./app/**/*.js', './test/*.js'], function() {
return gulp.src(['./app/js/blog.js', './test/posts.js'])
.pipe(named())
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./build'));
});
});
gulp.task('webpack', function() {
return gulp.src(['./app/js/blog.js', './test/posts.js'])
.pipe(named())
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./build'));
});
webpack.config.js
var path = require('path');
var babel = require('babel-loader');
module.exports = {
entry: {
app: './app/js/entry.js',
test: './test/posts.js'
},
output: {
filename: '[name].bundle.js',
sourceMapFilename: '[name].bundle.map'
},
devtool: '#source-map',
module: {
loaders: [
{
loader: 'babel',
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
query: {
presets: ['react', 'es2015']
}
}
]
},
resolve: {
root: path.resolve('./app'),
extensions: ['', '.js']
}
};
entry.js
import { posts } from './blog'
import { createStore } from 'redux'
createStore(posts)
blog.js
const posts = (state = [], action) => {
switch (action.type) {
case 'ADD_POST':
return post(undefined, action)
default:
return state
}
}
const post = (state = {}, action) => {
switch (action.type) {
case 'ADD_POST':
return { id: action.name, content: action.content }
}
}
// action creator
const addPost = (name, content) => {
return {
type: 'ADD_POST',
name,
content
}
}
export { posts, post, addPost }

How can I allow thrown errors to bubble up?

When I require a module that throws an error, it ends up returning an empty module instead of allowing that error to bubble up.
My code looks like:
var module = require("./path/to/the-module");
doSomethingWithComponent(module.mainComponent);
When there is no error thrown the module looks something like:
{
getters: []
actions: []
mainComponent: <TheComponent />
}
When there is an error it ends up like:
{}
An example of something that breaks the component looks like so:
var TheComponent = React.createClass({
getDefaultProps() {
return { x: this.props.x };
}
});
Using Chrome's "Pause On Caught Exceptions" option I've tracked down that the exception is happening but it being caught. I'm unable to track down where it's being caught at.
Here's a screenshot of the error happening:
Here's a screenshot highlighting how it gets set to an empty object:
My webpack config looks like:
var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var vendorLibs = {
_: 'lodash',
$: 'jquery',
jQuery: 'jquery',
bootstrap: 'bootstrap',
key: 'mousetrap',
React: 'react/addons',
debug: 'debug',
cx: 'classnames',
Immutable: 'immutable',
immstruct: 'immstruct',
interact: 'interact.js'
};
var providePlugin = {
Mixins: path.join(__dirname, 'src', 'app', 'mixins', 'index.js'),
Util: path.join(__dirname, 'src', 'app', 'lib', 'Util.js'),
reactor: path.join(__dirname, 'src', 'app', 'reactor.js')
};
var config = {
entry: {
app: './src/app/components/App.jsx',
vendor: _.values(vendorLibs)
},
output: {
path: './src/compiled/js',
filename: 'app.js'
},
module: {
loaders: [{
test: /^(?!.*node_modules)+.+\.jsx?$/,
loader: 'babel'
}, {
test: /\.json5$/,
loader: 'json5-loader'
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!autoprefixer-loader')
}, {
test: /\.less$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!autoprefixer-loader!less-loader')
}, {
test: /\.png$/,
loader: 'file'
}, {
test: /\.(ttf|eot|svg|woff2?)(\?v=(\d|\.)+)?$/,
loader: 'file?name=../fonts/[hash].[ext]'
}]
},
resolve: {
root: [
path.join(__dirname, 'src', 'app'),
path.join(__dirname, 'src', 'app', 'components'),
path.join(__dirname, 'src', 'less'),
path.join(__dirname, 'src', 'icons')
],
extensions: [
'', '.jsx', '.js'
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'),
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(['main'])
),
new webpack.ProvidePlugin(_.extend({}, vendorLibs, providePlugin)),
new ExtractTextPlugin('../css/app.css', { allChunks: true })
]
};
module.exports = config;
This app is also using NuclearJS and this component being required is a result of an action being dispatched so it's possible it could also be catching it there.
I'd like this error to not be caught so that I can spot it and resolve it without diving into the debugger. Does anyone know how I can make that happen?
Turns out there was a section of code with a try/catch that looked pretty innocent but led to this issue. After I found that I can address the problem. It looked like so:
try {
require(`modules/${variableValue}/index`);
} catch (err) {
dbg(`Cannot load module ${variableValue}`);
}
The dbg was not logging in the browser thus I didn't see it.

Categories

Resources