webpack.optimize.UglifyJSPlugin is producing junk JavaScript - javascript

Building my ES6 react project under OSX El Capitan using Webpack is a breeze. Something very weird happens when I do the same build on our pre-production environment, the built file comes out like this:
webpackJsonp([0],{102:function(module,exports,__webpack_require__) ...
...
var _createClass=function(){
function defineProperties(target,props){
for(;0<props.length;0++){
...
}
...
}
...
Take particular note of that for loop: for(;0<props.length;0++). That is very broken. What am I doing wrong? My config from UglifyJSPlugin:
new webpack.optimize.UglifyJsPlugin({
comments: false,
mangle: false,
compress: {
warnings: false
}
})
Any help would be very much appreciated.
Full Webpack Config:
module.exports = {
entry: {
isearch: 'components/isearch/index.js',
reactbundle: ['react', 'react-dom', 'whatwg-fetch', 'debounce-promise', 'deep-assign', 'redux', 'react-redux']
},
output: {
publicPath: '/assets/components/',
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
{ loader: 'style-loader', options: { includePaths: [] } },
{ loader: 'css-loader', options: { includePaths: [], modules: false } },
{ loader: 'sass-loader', options: { includePaths: [] } }
]
},
{
test: /\.gif$/,
exclude: '/node_modules/',
use: [{ loader: 'file-loader', options: { name: '[path][name].[hash].[ext]', context: 'react' } }]
}
]
},
resolve: { extensions: ['.js', '.jsx', '.scss'] },
devtool: 'cheap-module-source-map',
plugins: [
new CleanWebpackPlugin(['components'], {
root: path.resolve(__dirname, '../../public/assets'),
verbose: true,
dry: false
}),
new webpack.optimize.CommonsChunkPlugin('reactbundle'),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
comments: false,
mangle: false,
compress: {
warnings: false
}
})
]
};
Build Environment on which this fails: Ubuntu 12.04.5 LTS

Related

Webpack image - 404 not found

i'm starting a new project from a white sheet with a webpack configuration.
i'm trying to import an image in my html and i have this error in my console:
console error
Here you can show a part of my webpack configuration:
module.exports = {
entry: {
app: 'src/assets/js/index.js',
style: 'src/assets/scss/styles.scss',
},
output: {
filename: "src/assets/js/index.[hash:8].js",
path: path.join(__dirname, 'build')
},
devServer: {
contentBase: "./build"
},
resolve: {
modules: [path.resolve(__dirname), 'node_modules', '../../../../plugins/'],
extensions: ['.js'],
alias: {
jquery: path.join(__dirname, '/node_modules/jquery/dist/jquery.min.js'),
'slick-carousel': path.join(__dirname, '/node_modules/slick-carousel/slick/slick.js')
}
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true // set to true if you want JS source maps
}),
new OptimizeCSSAssetsPlugin({})
]
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
{
loader: 'css-loader',
options: { importLoaders: 1 }
},
{
loader: 'postcss-loader',
options: {
config: {
path: path.resolve(__dirname + '/postcss.config.js')
}
}
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
publicPath: './img/',
outputPath: 'img'
}
}
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
publicPath: './fonts/',
outputPath: 'fonts'
}
}
]
}
]
},
My folders structure:
folders
the code to import the image:
<section class="header">
<h1><img src='../img/logo-texte.png' alt="Le Grand Dressing"/></h1>
</section>
Someone have an idea ? :( thanks to you

My Vue build in webpack produces a huge (850kb) vendor file, how do I make it the expected 85kb?

Solved:
devtool: '#eval-source-map'
Includes a source map in the output
Original issue
As stated, the webpack build produces an enormous bundle/vendor file with Vue as my only import. I cannot see for the life of me how people get it down to 80kb.
As far as I can see, there is a vue-loader and the file gets minified, so why would it come out enormous?
var path = require('path') var webpack = require('webpack')
module.exports = { entry: './src/main.js', output: {
path: path.resolve(__dirname, './static'),
publicPath: '/static/',
filename: 'js/login-view.js' }, module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
}, {
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]',
useRelativePath: true,
publicPath: './static/images/'
}
}
] }, resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json'] }, devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true }, performance: {
hints: false }, devtool: '#eval-source-map' }
if (process.env.NODE_ENV === 'production') { // module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: false,
// compress: true,
compress: {
warnings: false
},
mangle: true,
}),
new webpack.LoaderOptionsPlugin({
minimize: true
}) ]) }
devtool: '#eval-source-map'
was the culprit. It was getting included in all builds and it puts the sourcemap in the files. I removed this and dropped the file to ~90kb.

How to use Sass-loader with React and Webpack?

I'm using React 16, Webpack 3 and Bootstrap 4 beta.
I'm trying to load .scss files into React using something similar to the following import styles from './styles/app.scss'. At the moment I am using import style from 'style-loader!css-loader!sass-loader!applicationStyles';. I would like to move away from using the sass-loader in the .js file.
Any help improving up my webpack config would also be most welcome as it's a mess...
Here's my webpack file:
const webpack = require('webpack');
const path = require('path');
const envFile = require('node-env-file');
require('babel-polyfill');
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
try {
envFile(path.join(__dirname, 'config/' + process.env.NODE_ENV + '.env'))
} catch (e) { }
module.exports = {
entry: [
'script-loader!jquery/dist/jquery.min.js',
'babel-polyfill',
'whatwg-fetch',
'./app/app.jsx',
],
externals: {
jQuery: 'jQuery'
},
plugins: [
new webpack.ProvidePlugin({
'$': 'jQuery',
'jQuery': 'jQuery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default'],
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
API_KEY: JSON.stringify(process.env.API_KEY),
API_DOMAIN: JSON.stringify(process.env.API_DOMAIN),
API_FILE_DOMAIN: JSON.stringify(process.env.API_FILE_DOMAIN),
}
}),
],
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/'
},
resolve: {
modules: [
__dirname,
'node_modules',
'./app/api',
'./app/constants',
],
alias: {
applicationStyles: 'app/styles/app.scss'
},
extensions: ['.js', '.jsx']
},
devServer: { historyApiFallback: { index: 'public/index.html' }, },
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/
},
// {
// loader: 'sass-loader',
// options: {
// includePaths: [ path.resolve(__dirname, './node_modules/bootstrap/scss')]
// },
// test: /\.scss?$/,
// },
{
loader: 'css-loader',
options: {
includePaths: [path.resolve(__dirname, './node_modules/react-table/react-table.css')]
},
test: /\.css?$/,
}
],
// I tried this but it gave me an error
// rules:[
// {
// test: /\.scss$/,
// use: [
// { loader: "style-loader" },
// { loader: "css-loader" },
// { loader: "sass-loader" }
// ]
// }
// ],
},
devtool: process.env.NODE_ENV === 'production' ? undefined : 'eval-source-map'
};
Here are the imports in my App.jsx file
import 'bootstrap'
import style from 'style-loader!css-loader!sass-loader!applicationStyles';
import 'style-loader!react-table/react-table.css';
I added rules to my webpack - see below:
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: { loader: 'babel-loader'}
},
{
test: /\.css?$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
]
},
{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
},
]
},
so now I can just do:
import style from 'applicationStyles';
import 'react-table/react-table.css';
Make it more simple.
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module: {
rules: [
{
test: /\.(css|scss)$/,
use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
],
},
{
test: /\.s[ac]ss$/i,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
options: {
modules: true,
localsConvention: "camelCase",
sourceMap: true,
},
},
{
loader: "sass-loader",
options: {
sourceMap: true,
},
},
],
}
}

Unexpected character '#' You may need an appropriate loader to handle this file type

This is what I get when I try to run webpack: the error I get is:
"ERROR in ./v3/app/styles/main.scss
Module parse failed: /Users/vovina/widget-login-react/v3/app/styles/main.scss Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type."
it can't resolve #import, any ideas on this?
my webpack config is as follow:
const childProcess = require('child_process')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const trimEnd = require('lodash/trimEnd')
const webpack = require('webpack')
const path = require('path')
const ENV = {
NODE_ENV: process.env.NODE_ENV,
API: 'https://accounts' + (process.env.NODE_ENV === 'prd' ? '' : '-'
+ process.env.NODE_ENV),
BUILD_VERSION: trimEnd(childProcess.execSync('git rev-list HEAD --
count').toString(), '\n'),
BUILD_DATE: trimEnd(childProcess.execSync('git log --format="%cd" -n
1').toString(), '\n'),
BUILD_COMMIT_ID: trimEnd(childProcess.execSync('git log --format="%h"
-n 1').toString(), '\n')
}
const prodLikeEnvironment = process.env.NODE_ENV === 'stg' ||
process.env.NODE_ENV === 'prd'
const CSS_MAPS = !prodLikeEnvironment
module.exports = {
entry: {
init: [
'./app/init.js'
],
login: [
'./app/login.js'
],
authentication: [
'./v3/app/authenticator.js'
],
common: [
'./app/common.js'
]
},
target: 'web',
output: {
path: path.join(__dirname, 'dist', process.env.NODE_ENV),
pathinfo: true,
publicPath: '/assets/widgets/login/v2/',
filename: '[name].bundle.js',
chunkFilename: '[id].bundle.js',
libraryTarget: 'umd'
},
resolve: {
alias: {
'react': 'preact-compat',
'react-dom': 'preact-compat'
},
modules: [
path.resolve('./app'),
path.resolve('./node_modules')
]
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: [/bower_components/, /node_modules/]
},
{
// Transform our own .(scss|css) files with PostCSS and CSS-modules
test: /\.(scss|css)$/,
include: [path.resolve(__dirname, 'v3/app')],
options: {
sourceMap: true
},
loader: [
`style-loader?singleton`,
`css-loader?modules&importLoaders=1&localIdentName=
[local]${process.env.CSS_MODULES_IDENT ||
'_[hash:base64:5]'}&sourceMap=${CSS_MAPS}`,
'postcss-loader',
`sass-loader?sourceMap=${CSS_MAPS}`
].join('!')
},
{
test: /\.(scss|css)$/,
exclude: [path.resolve(__dirname, 'v3/app')],
options: {
sourceMap: true
},
loader: [
`style-loader?singleton`,
`css-loader?sourceMap=${CSS_MAPS}`,
`postcss-loader`,
`sass-loader?sourceMap=${CSS_MAPS}`
].join('!')
},
{
test: /\.(svg|eot|woff|woff2?|ttf|otf)$/,
use: 'base64-font-loader'
},
{
test: /.json$/,
loader: 'json'
},
{
test: /\.jpe?g$|\.gif$|\.png$/,
use: 'base64-image-loader'
},
{
test: /\.html?$/,
loader: 'html'
},
{
test: /\.js$/,
loader: 'strip-loader?strip[]=debug,strip[]=console.log,strip[]=console.debug,strip[]=console.info'
}
]
},
plugins: [
new webpack.LoaderOptionsPlugin({
minimize: true
// postcss: [
// autoprefixer({ browsers: 'last 2 versions' })
// ]
}),
new CopyWebpackPlugin([
{ from: 'public' }
]),
new ExtractTextPlugin('[name].bundle.css'),
new webpack.DefinePlugin({
ENV: JSON.stringify(ENV),
// Only used for react prod bundle. Refer to ENV.NODE_ENV for business
logic
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
output: {
comments: false
},
compress: {
unsafe_comps: true,
properties: true,
keep_fargs: false,
pure_getters: true,
collapse_vars: true,
unsafe: true,
warnings: false,
screw_ie8: true,
sequences: true,
dead_code: true,
drop_debugger: true,
comparisons: true,
conditionals: true,
evaluate: true,
booleans: true,
loops: true,
unused: true,
hoist_funs: true,
if_return: true,
join_vars: true,
cascade: true,
drop_console: true
}
})
]
}
You are using the (scss|css) twice in your configuration file.
Remove that and use the code posted blow:
Before using, you must first npm install raw-loader.
I think you've already installed the sass-loader.
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw-loader'
},
// // css global which not include in components
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({
use: 'raw-loader'
})
},
{
test: /\.scss$/,
include: helpers.root('src', 'app'),
use: ['raw-loader', 'sass-loader']
},
// // SASS global which not include in components
{
test: /\.scss$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({
use: ['raw-loader', 'sass-loader']
})
}
Add my root()function.
var path = require('path');
var _root = path.resolve(__dirname, '..');
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [_root].concat(args));
}
exports.root = root;
Hope this will work.

Cannot find update. Need to do a full reload! in webpack

This is my file webpack.config.js . Although I added ['react-hot' ,'babel']. But can resolve it.
var webpack = require('webpack');
var path = require('path');
var APP_DIR = path.resolve(__dirname, 'client/');
var devFlagPlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'true'))
});
var config = {
cache: true,
devtool: 'eval', // 'source-map', 'eval'
entry: [
'webpack-dev-server/client?http://localhost:3000/',
'webpack/hot/only-dev-server',
'./client/app.jsx'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'client'),
exclude: /node_modules/,
loader: ['react-hot' ,'babel'],
query: {
cacheDirectory: true,
presets: ['react', 'es2015']
}
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
},
{
test: /\.(jpe?g|png|gif|jpg|svg)$/i,
loaders: [
'file?images/hash=sha512&digest=hex&name=../build/img/[hash].[ext]',
'image-webpack?{optimizationLevel: 9, interlaced: false, pngquant:{quality: "65-90", speed: 4}, mozjpeg: {quality: 65}}'
]
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file?name=../build/fonts/[name].[ext]'
}
]
},
sassLoader: {
includePaths: [path.resolve(__dirname, "./client/assets/css/")]
},
plugins: [
devFlagPlugin,
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: true
},
output: {
comments: true,
}
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
}
module.exports = config;
I believe your problem is you need to use babel-preset-react-hmre in order for it to work properly. More info here here.
For example
{
test: /\.jsx?$/,
include: path.join(__dirname, 'client'),
exclude: /node_modules/,
loader: ['react-hot' ,'babel'],
query: {
cacheDirectory: true,
presets: ['react', 'es2015', 'react-hmre']
}
},

Categories

Resources