How to minimize javascript with Webpack? - javascript

I'm trying to minimize my bundle.js file with webpack, but getting errors in my config:
module.exports = {
entry: "./entry.js",
output: {
devtoolLineToLine: true,
sourceMapFilename: "./bundle.js.map",
pathinfo: true,
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true
})
]
};
The error:
/Users/leongaban/Projects/TickerTags/ionic/TickerTags/www/webpack.config.js:16
new webpack.optimize.UglifyJsPlugin({
^
ReferenceError: webpack is not defined

Seems like you're missing var webpack = require('webpack'); at the top of your configuration file.
It works for me this way

Related

How to solve ChunkLoadError: Loading hot update chunk second_app failed in webpack 5?

while setup a new project for development, the app is not hot reloading. The app consists of multiple apps separated in its different folders.Currently, there are 2 apps html_nodes_prototype and second_app in src/apps folder. Each app consist of index.html, style.css and main.js when I visit the link http://localhost:8080/second_app/second_app.html, the app shows but If I change something in src/apps/second_app/main.js. It doesn't hot reload, I've to manually reload to get changes. I've set up a webpack-dev-server. Error prompts in the console. I couldn't figure out what's wrong with the config file.
Error in console
[HMR] Update failed: ChunkLoadError: Loading hot update chunk second_app failed.
(missing: http://localhost:8080/second_app.5b0047c2bf2b48c8a084.hot-update.js)
at http://localhost:8080/second_app/second_app.bundle.js:987:26
at new Promise (<anonymous>)
at loadUpdateChunk (http://localhost:8080/second_app/second_app.bundle.js:982:20)
at http://localhost:8080/second_app/second_app.bundle.js:1411:29
at Array.forEach (<anonymous>)
at Object.__webpack_require__.hmrC.jsonp (http://localhost:8080/second_app/second_app.bundle.js:1406:22)
at http://localhost:8080/second_app/second_app.bundle.js:819:45
at Array.reduce (<anonymous>)
at http://localhost:8080/second_app/second_app.bundle.js:815:53
paths.js
const path = require("path");
module.exports = {
// Source files
src: path.resolve(__dirname, "../src"),
// Production build files
build: path.resolve(__dirname, "../dist"),
// public path
public: path.resolve(__dirname, "../public/"),
};
webpack.dev.js
const common = require("./webpack.common");
var HtmlWebpackPlugin = require("html-webpack-plugin");
const merge = require("webpack-merge").merge;
const paths = require("./paths");
module.exports = merge(common, {
mode: "development",
output: {
filename: "[name]/[name].bundle.js",
path: paths.build,
},
module: {
rules: [
{ test: /\.scss$/, use: ["style-loader", "css-loader", "sass-loader"] },
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
],
},
devServer: {
historyApiFallback: true,
// contentBase: paths.build,
open: true,
compress: true,
hot: true,
port: 8080,
},
plugins: [
new HtmlWebpackPlugin({
filename: "html_nodes_prototype/html_nodes_prototype.html",
title: "HTML Nodes",
template: "src/apps/html_nodes_prototype/index.html",
chunks: ["html_nodes_prototype", "vendor"],
}),
new HtmlWebpackPlugin({
filename: "second_app/second_app.html",
title: "Second app",
hot: true,
template: "src/apps/second_app/index.html",
chunks: ["second_app", "vendor"],
}),
],
});
webpack.common.js
const paths = require("./paths");
module.exports = {
mode: "development",
entry: {
html_nodes_prototype: paths.src + "/apps/html_nodes_prototype/main.js",
second_app: paths.src + "/apps/second_app/main.js",
vendor: paths.src + "/apps/_vendor/vendor.js",
},
module: {
rules: [{ test: /\.m?js$/, use: ["babel-loader"] }],
},
};
Adding runtimeChunk: 'single' to webpack.dev.js works for me. Found the answer here
module.exports = {
...,
optimization: {
runtimeChunk: 'single'
},
...
}

webpack error configuration.module has an unknown property 'loaders'

When I run the server using npm run start, I am getting following error:
✖ 「wds」: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration has an unknown property 'debug'. These properties are valid:
object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, externals?, infrastructureLogging?, loader?, mode?, module?, name?, node?, optimization?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, serve?, stats?, target?, watch?, watchOptions? }
The 'debug' property was removed in webpack 2.0.0.
Loaders should be updated to allow passing this option via loader options in module.rules.
Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:
plugins: [
new webpack.LoaderOptionsPlugin({
debug: true
})
]
- configuration.module has an unknown property 'loaders'. These properties are valid:
object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPresence?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
-> Options affecting the normal modules (`NormalModuleFactory`).
My webpack.config.js is as following:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: [
'./src/Main.js'
],
output: { path: __dirname, filename: 'bundle.js' },
cache: true,
debug: true,
devtool: 'source-map',
module: {
loaders: [
{
test: /\.glsl$/,
loader: 'webpack-glsl',
include: [
path.resolve(__dirname, 'src', 'shaders')
]
}
]
},
devServer: {
compress: true,
disableHostCheck: true,
},
plugins: [
new webpack.LoaderOptionsPlugin({
debug: true
})
]
};
What is your webpack version ?
As for webpack 4 - you need to change from "loaders" to "rules"
module: {
rules: [
{ test: /\.glsl$/, use: 'webpack-glsl' }
]
...
Hope this is the answer you are expecting.
You should change loaders to rules in webpack 4:
change loaders
to rules .See Loaders
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: [
'./src/Main.js'
],
output: { path: __dirname, filename: 'bundle.js' },
devtool: 'source-map',
module: {
rules: [
{ test: /\.glsl$/, use: 'webpack-glsl' }
]
},
devServer: {
compress: true,
disableHostCheck: true,
},
plugins: [
new webpack.LoaderOptionsPlugin({
debug: true
})
]
};
to see debug property.See Debug

Webpack-Dev-Server not showing latest files on change

I am trying to get a project running that uses a webpack dev server with HMR and source-mapping but am running into an issue. When I use webpack alone with my configuration file the source-maps are indicated in the console output and HMR works on page-refresh, but there is no server. When I try to instead run the script using webpack-dev-server there is no indication in the console that source-maps are being generated and changes are not being rendered ( either automatically or on page refresh ) when recompilation is appearing in the console output.
Here is my configuration file
/*
Webpack Configuration File
webpack.config.js
===
Webpack configuration file for the, "Debugging Webpack Issues" project.
#version:0.1.1
*/
const webpack = require( "webpack" );
const path = require( "path" );
const htmlWebpackPlugin = require( "html-webpack-plugin" );
const BUILD_PATH = path.resolve( __dirname, "../build" );
const SOURCE_PATH = path.resolve( __dirname, "../src" );
console.log(BUILD_PATH);
console.log(SOURCE_PATH);
let config = {
entry: SOURCE_PATH + "/index.js",
output: {
path: BUILD_PATH + "/rsc/scripts/",
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
options: {
"presets" : [ "es2015", "react" ]
},
exclude: [/node_modules/],
include: SOURCE_PATH
},
{
test: /\.css$/,
use: [ "style-loader", "css-loader" ],
include: SOURCE_PATH,
exclude: [/node_modules/]
}
]
},
devServer: {
compress: true,
port:9000,
open: true,
hot: true,
contentBase: BUILD_PATH
},
devtool: "source-map",
watch: true,
target: "web",
plugins: [
new htmlWebpackPlugin({
title: "Example React App",
filename: "../../index.html",
template: SOURCE_PATH + "/template.html"
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
]
};
module.exports = config;
I am aware that webpack-dev-server may not be updating because it is trying to load from a static location, but I have attempted changes to my file that others specified in their projects ( such as adding publicPath to the file ) with this issue without success.
Webpack's publicPath value needs to be relative to the build directory in the output.
Here is a working version of my webpack configuration file :
/*
Webpack Configuration File
webpack.config.js
===
Webpack configuration file for the, "Debugging Webpack Issues" project.
#version:0.1.1
*/
const webpack = require( "webpack" );
const path = require( "path" );
const htmlWebpackPlugin = require( "html-webpack-plugin" );
const BUILD_PATH = path.resolve( __dirname, "../build" );
const SOURCE_PATH = path.resolve( __dirname, "../src" );
const PUBLIC_PATH = "/rsc/scripts/";
console.log(BUILD_PATH);
console.log(SOURCE_PATH);
let config = {
entry: SOURCE_PATH + "/index.js",
output: {
path: BUILD_PATH + PUBLIC_PATH,
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader",
options: {
"presets" : [ "es2015", "react" ]
},
exclude: [/node_modules/],
include: SOURCE_PATH
},
{
test: /\.css$/,
use: [ "style-loader", "css-loader" ],
include: SOURCE_PATH,
exclude: [/node_modules/]
}
]
},
devServer: {
compress: true,
port:9000,
open: true,
hot: true,
contentBase: BUILD_PATH,
publicPath: PUBLIC_PATH
},
devtool: "source-map",
watch: true,
target: "web",
plugins: [
new htmlWebpackPlugin({
title: "Example React App",
filename: "../../index.html",
template: SOURCE_PATH + "/template.html"
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
]
};
module.exports = config;
Anyone with this problem should make sure that a publicPath is set in the devServer configuration options. The publicPath should be treated as the path ( relative to the build directory ) that your Server's html file should look to grab bundle.js from.
My project structure in my Build folder looks like:
./build
./build/rsc/scripts/bundle.js
./build/index.html
so my publicPath needed to be set to /rsc/scripts so that it knew where to get the virtual file from.
In my case , project was generated by create-react-app.
My solution is:
Find
./node_modules/react-scripts/config/webpackDevServer.config.js
locate below code:
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebook/create-react-app/issues/387.
disableDotRule: true,
index: paths.publicUrlOrPath,
},
Remove the above code, and update the above as below:
historyApiFallback: true,
hot: true,

Can't transpile es6; import declaration error

I've ready many questions and articles on the subject, but nothing seems to work. My error is this:
SyntaxError: import declarations may only appear at top level of a module
It's a result of me being unable to properly transpile es6 code. Here's my webpack and .babelrc:
webpack:
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
var path = require('path')
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client?reload=true',
path.join(__dirname, './app/index.js')
],
module: {
loaders: [{
test: [/\.js$/,/\.jsx$/],
loader: "babel-loader",
include: [
path.resolve(__dirname, "node_modules/flash-notification-react-redux"),
path.resolve(__dirname, "./app")
],
},{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract('css!sass')
},{
test: /\.(png|jpg)$/,
loader: 'url-loader?limit=8192'
}]
},
output: {
filename: 'index.bundle.js',
path: __dirname + '/dist',
publicPath: '/'
},
plugins: [
HTMLWebpackPluginConfig,
new ExtractTextPlugin('public/style.css', {
allChunks: true
}),
new webpack.HotModuleReplacementPlugin(),
]
}
.babelrc
{
presets: [ 'es2015', 'stage-0', 'react'],
plugins: ['transform-decorators-legacy']
}
I've tried various things (such as using 'babel-preset-es2015', as well as the stage-0 addition), but nothing seems to work.
This code in one of my Components:
import GrowlerComponent from 'flash-notification-react-redux'
is converted to this in index.bundle.js, which actually throws the error:
import GrowlerReducer from "./src/reducer/growler.reducer";

Webpack 2 beta + history API fallback not working

Today, after removing my node_modules and reinstalling them using npm install, my project doesn't seem to work.
Here's my webpack config
const webpack = require('webpack');
const path = require('path');
const srcPath = path.join(__dirname, './client');
const nodeEnv = process.env.NODE_ENV || 'development';
const isProd = nodeEnv === 'production';
module.exports = {
devtool: isProd ? 'hidden-source-map' : 'cheap-module-eval-source-map',
context: path.join(__dirname, './client'),
entry: {
js: './index.js',
vendor: ['react']
},
output: {
path: path.join(__dirname, './static'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.html$/,
loader: 'file',
query: {
name: '[name].[ext]'
}
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loaders: ['babel-loader']
},
{
test: /\.(png|jpg|gif|otf|eot|svg|ttf|woff|woff2)/,
loader: 'url-loader'
},
{
test: /\.(txt|json)/,
loader: 'raw-loader'
}
],
},
resolve: {
extensions: ['', '.js', '.jsx'],
modules: [
path.resolve('./client'),
'node_modules'
],
alias: {
stores: `${srcPath}/stores/`,
components: `${srcPath}/components/`,
services: `${srcPath}/services`,
models: `${srcPath}/models`,
constants: `${srcPath}/constants`,
sources: `${srcPath}/sources`,
images: `${srcPath}/assets/images`,
appConstants: isProd ? `${srcPath}/constants/_prod` : `${srcPath}/constants/_dev`
}
},
plugins: [
new webpack.IgnorePlugin(/regenerator|nodent|js\-beautify/, /ajv/),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity,
filename: 'vendor.bundle.js'
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: isProd
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: !isProd
},
output: {
comments: !isProd
},
sourceMap: !isProd
}),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(nodeEnv) }
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.OccurrenceOrderPlugin()
],
devServer: {
contentBase: './client',
hot: true,
port: 3000,
historyApiFallback: true
}
};
My "client" folder with index.html and the rest of my code are in the same folder as webpack config.
Webpack does succesfully build, but going to localhost:3000, I get error message: "Cannot GET /"
Going to localhost:3000/client/index.html does serve my index.html, but my built files inserted using
<script src="./vendor.bundle.js"></script>
<script src="./bundle.js"></script>
doesn't load (GET to "http://localhost:3000/client/bundle.js" results in 404)
Anyone knows what's going on? I can't fix this issue, and I think I've tried everything, from changing path, publicPath to changing contentBase and moving my static files to different folder.
It's very strange, since this issue appeared only after reinstalling my project dependencies.
Every bit of help is much appreciated. Thanks.
There was an issue in webpack-dev-server#2.1.0-beta.3, which caused the contentBase option to be ignored. Could you try upgrading to 2.1.0-beta.4? It was just released.

Categories