Webpack 2 - Suppress chunk files - javascript

As we are putting this output on a load balancer (not using sticky), we need to place the output of these files without chunks (neither hashes).
These are the main two files for webpack configuration.
webpack.common.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const helpers = require('./helpers');
const STATIC_TRANSLATION_MAP = require('../TranslationMap.json');
module.exports = {
entry: {
app: ['./src/public/main.ts'],
vendor: './src/public/vendor.ts',
polyfills: './src/public/polyfills.ts'
},
output: {
path: helpers.root('dist/public')
},
module: {
rules: [
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader', 'angular2-router-loader']
},
{
test: /\.html$/,
loader: 'html-loader?-minimize'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[ext]'
},
{
test: /\.styl$/,
include: helpers.root('src', 'public', 'app'),
use: [
'raw-loader',
'stylus-loader'
]
},
{
test: /\.styl$/,
include: helpers.root('src', 'public'),
exclude: helpers.root('src', 'public', 'app'),
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
'stylus-loader'
]
})
},
{
test: /\.css$/,
include: helpers.root('src', 'public', 'assets', 'css'),
loader: 'raw-loader'
},
{
test: /\.xlf$/,
loader: 'raw-loader'
}
]
},
resolve: {
extensions: ['.webpack.js', '.web.js', '.ts', '.js'],
alias: {}
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'src/public/index.html'
}),
new webpack.DefinePlugin({
'process.env': {
'LOCALE_LIST': JSON.stringify(Object.keys(STATIC_TRANSLATION_MAP))
}
})
]
};
webpack.prod.js
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const commonConfig = require('./webpack.common.js');
const helpers = require('./helpers');
const prodEnv = 'production';
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
output: {
filename: '[name].js',
chunkFilename: '[name].js'
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: {
keep_fnames: true
}
}),
new webpack.LoaderOptionsPlugin({
htmlLoader: {
minimize: false
}
}),
new ExtractTextPlugin('[name].css'),
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(prodEnv)
}
})
]
});
But for my surprise, I noticed webpack is producing extra files. Can you see those ones with numbers? (From 0 to 19). I'm not sure from where they're coming from, and every content of those starts with webpackJsonp.
Is there a way to disable this chunk feature and just produce the three files from entry?

What is happening?
But for my surprise, I noticed webpack is producing extra files. Can you see those ones with numbers? (From 0 to 19)
output.chunkFilename
This option determines the name of non-entry chunk files.
By default [id].js is used or a value inferred from output.filename (name is replaced with id):
Non-entry chunks (external)
./dist/[0].js
./dist/[1].js
./dist/[2].js
./dist/[3].js
...
Entry-chunks from webpack.config.entry
./dist/app.js
./dist/vendor.js
...
How to fix it?
Currently CommonChunkPlugin only receives modules imported from entry chunks.
webpack/issues/4392
Workarounds / hacks
This concept may be used to obtain implicit common vendor chunks:
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: function (module) {
// this assumes your vendor imports exist in the node_modules directory
return module.context && module.context.indexOf("node_modules") !== -1;
}
})
Passing the minChunks property a function
webpack/issues/2855#issuecomment-239606760
https://stackoverflow.com/a/39401288/6836839

Related

How do I configure webpack for scss and bootstrap with ASP.NET project?

I've got webpack up and running and can't quite figure our how to get .scss file compiled to be used with custom styling such as colors etc. Bootstrap is otherwise loaded fine.
Here's my webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = (env = {}, argv = {}) => {
const isProd = argv.mode === 'production';
const config = {
mode: argv.mode || 'development', // we default to development when no 'mode' arg is passed
optimization: {
minimize: true
},
entry: {
main: './src/main.js'
},
output: {
filename: isProd ? 'bundle-[chunkHash].js' : '[name].js',
path: path.resolve(__dirname, '../wwwroot/dist'),
publicPath: "/dist/"
},
plugins: [
new MiniCssExtractPlugin({
filename: isProd ? 'style-[contenthash].css' : 'style.css'
}),
new CompressionPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
threshold: 10240,
minRatio: 0.8
}),
new HtmlWebpackPlugin({
template: '_LayoutTemplate.cshtml',
filename: '../../Views/Shared/_Layout.cshtml', //the output root here is /wwwroot/dist so we ../../
inject: false
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.(png|jpg|gif|woff|woff2|eot|ttf|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]',
outputPath: 'assets/'
}
}
]
}
};
return config;
};
I have node-sass installed which I think compiles it? Just not sure how to get it going.
Thanks,
You need to import your CSS into your entrypoint. So in main.js, import your scss file like this...
import './path-to/file.scss

Large console output produced by mini-css-extract-plugin

Been trying to research this but it doesn't seem as if any else has this, or see this as an issue.
I am using mini-css-extract-plugin(MiniCssExtractPlugin) in my webpack.config.js.
However, when I run webpack the console is littered with hundreds of instances of something similar to this...
Child mini-css-extract-plugin ../../../node_modules/css-loader/index.js??ref--6-1!../../../node_modules/postcss-loader/src/index.js!../../../node_modules/sass-loader/lib/loader.js!ui/radiolist-toggler/RadioListToggler.scss:
Entrypoint mini-css-extract-plugin = *
[../../../node_modules/css-loader/index.js?!../../../node_modules/postcss-loader/src/index.js!../../../node_modules/sass-loader/lib/loader.js!./ui/radiolist-toggler/RadioListToggler.scss] /Users/~~~/git/user-section/node_modules/css-loader??ref--6-1!/Users/~~~/git/user-section/node_modules/postcss-loader/src!/Users/~~/git/user-section/node_modules/sass-loader/lib/loader.js!./ui/radiolist-toggler/RadioListToggler.scss 5.33 KiB {mini-css-extract-plugin} [built]
+ 1 hidden module
I need to scroll up for a good few seconds to be able to see all my assets etc.
I am pretty new to webpack, so not exactly sure how to prevent this from being output to the console?
Below is my webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const modernizr = require("modernizr");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, 'src/main/client'),
entry: './index',
devtool: 'cheap-module-source-map',
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
mangle: true,
compress: true,
ecma: 6
},
sourceMap: true
}),
new OptimizeCssAssetsPlugin({}),
],
splitChunks: {
chunks: 'all'
}
},
plugins: [
new CompressionPlugin({
test: /\.js$|\.css$|\.html$|\.(png|svg|jpg|gif)$/,
cache: true,
filename: '[path].gz[query]',
algorithm: 'gzip',
threshold: 10240
}),
new CleanWebpackPlugin([
'./target/webapp'
]),
new HtmlWebpackPlugin({
template: './index.html',
filename: '../index.html',
xhtml: true
}),
new MiniCssExtractPlugin({
filename: "[name].css",
}),
new CopyWebpackPlugin([{
from: '../webapp/**/*',
to: '../'
}]),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
],
output: {
publicPath: '/app/',
filename: '[name].bundle.js',
chunkFilename: '[id].js',
path: path.resolve(__dirname, 'target/webapp/app/')
},
module: {
rules: [{
loader: "webpack-modernizr-loader",
test: /\.modernizrrc\.js$/
},
{
test: /\.html$/,
exclude: /node_modules/,
use: {
loader: 'html-loader'
}
},
{
test: /\.s?css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
importLoaders: 1
}
},
{
loader: 'postcss-loader'
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: './assets/fonts/'
}
}]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: ["#babel/env"]
}
}
],
},
resolve: {
alias: {
// You can add comment "Please do not delete this file" in this file
modernizr$: path.resolve(__dirname, "./.modernizrrc.js")
}
}
}
#mcclosa mentioned this as a comment but in case anyone should look at this question, see no answer and click away, the solution is to add the stats option to your webpack.config.js file as follows:
module.exports = {
stats: { children: false },
}
The above option uses the children: false option suggested by #mcclosa, which does successfully remove the junk output by mini-css-extract-plugin, but I find using the preset stats: "minimal" produces a much nicer overall output. Using:
module.exports = {
stats: "minimal",
}
..gives me the following tiny output whenever my build has no errors:
i 「wdm」: Compiling...
i 「wdm」: 69 modules
i 「wdm」: Compiled successfully.
..as opposed to dozens of lines of useless build data, but it will continue to give give error information when errors are present.
Unfortunately, mini-css-extract-loader does not have a setting to control the verbosity of its log output.
Setting stats.children to false or "minimal" in your webpack.config.js can remove a lot of other useful output like your bundle names and sizes, entry point information, time taken to build, legitimate warnings and errors from other plugins that you may want to keep, etc.
Instead it seems that we must add a plugin that executes on the compiler's done hook to remove items from the stats.compilation object associated with mini-css-extract-plugin.
This example plugin should work:
class CleanupMiniCssExtractPlugin {
apply(compiler) {
compiler.hooks.done.tap("CleanupMiniCssExtractPlugin", stats => {
if (this._children) {
const children = stats.compilation.children;
if (Array.isArray(children)) {
stats.compilation.children = children.filter(
child => child.name.indexOf("mini-css-extract-plugin") == -1
);
}
}
});
}
}
Or you can use this npm package: https://www.npmjs.com/package/cleanup-mini-css-extract-plugin

how to add css files in index.html using web pack

I am new to webpack & want to add all the css files bundled and added to to the index.html file in dist.
my webpack.config.js file
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const helpers = require('./helpers');
module.exports = function(env) {
return {
entry: {main:'./app/index.js',
vendor: 'moment'
},
resolve: {
extensions: ['.css', '.js']
},
output: {
filename: '[name].[chunkhash].js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [{
test: /\.css$/,
include: helpers.root('app'),
use: ExtractTextPlugin.extract({
fallback: "css-loader",
use: 'style-loader'
})
},
{
test: /\.html$/,
loader: 'html-loader'
}
]},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', , 'manifest']
}),
new ExtractTextPlugin('styles.css'),
new HtmlWebpackPlugin({
template: 'app/index.html',
inject: 'body'
})
]
}
};
However it does not create styles.css file.
Thanks in advance.

Webpack doesn't catch the changes in Typescript files

I am working on an Angular project and use Webpack bundler. Everything was working fine until Webpack started to ignore my changes to Typescript files. When I change a Typescript file, Webpack first says:
[WDS] App updated. Recompiling...
followed by:
[WDS] Nothing changed.
Also, killing webpack-dev-server and rebuilding the sources doesn't make any difference. The changes I make to TS files are not applied in any way.
EDIT: Loader setup on request (which is exactly the same as in the Angular Developer Guide):
webpack.common.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['', '.js', '.ts']
},
module: {
loaders: [
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader']
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file?name=assets/[name].[hash].[ext]'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw'
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
webpack.dev.js:
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: helpers.root('dist'),
publicPath: 'http://localhost:8080/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
plugins: [
new ExtractTextPlugin('[name].css')
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
});

webpack production setup - vendors output js always has different chunk hash even though nothing's changed

The follow production webpack.config file mostly works (builds, runs ok), but one nagging problem. I set up vendor and app js outputs precisely to separate vendor code (since those don't change very often). However, with the .config setup, even if there is no change, I always get a different chunk hash for vendor and app.js. I must be setting this wrong somehow but I have no idea what it could be. Please help!
var path = require('path');
var webpack = require('webpack');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var AssetsPlugin = require('assets-webpack-plugin');
var ChunkManifestPlugin = require('chunk-manifest-webpack-plugin');
var app_dir = path.join(__dirname, 'app');
var config = {
entry: {
vendors: ['react', 'react-dom', 'moment'],
app: path.resolve(__dirname, 'app/Main.js')
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js'
},
module: {
loaders: [{
test: /\.jsx?$/, // A regexp to test the require path. accepts either js or jsx
exclude: [node_modules_dir],
loader: 'babel', // The module to load. "babel" is short for "babel-loader"
},
// LESS
{
test: /\.less$/,
loader: 'style!css!less'
},
{
test: /\.css$/, // Only .css files
loader: 'style!css' // Run both loaders
},
{
test: /\.(png|jpg)$/,
loader: 'url?limit=25000'
},
{ test: /\.gif$/, loader: "url-loader?mimetype=image/png" },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?name=[name].[ext]" }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: "vendors",
minChunks: Infinity
}),
new AssetsPlugin({
filename: 'webpack-assets.js',
path: path.resolve(__dirname, 'dist'),
processOutput: function (assets) {
return 'window.staticMap = ' + JSON.stringify(assets);
}
}),
new ChunkManifestPlugin({
filename: "chunk-manifest.json",
manifestVariable: "webpackManifest"
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"production"'
},
'__appSettings': {
'apiGatewayDomain': '"http://localhost:8088"',
'enableDevTools': false,
'enableReduxLogger': false
},
__version: JSON.stringify(require(__dirname +"/package.json").version)
}),
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!isomorphic-fetch',
'configureApplicationStore': 'exports?configureStore!' + app_dir + '/global/redux/ConfigureStore.prod.js'
})
]
};
module.exports = config;
If there are other glaring issues with this setup, please let me know as well. Thanks!
use the "key sort" to fixed vendor.
you entry just like this:
entry: {
a_vendors: ['react', 'react-dom', 'moment'],
z_app: path.resolve(__dirname, 'app/Main.js')
},
the vendor will fixed.
more detail:
https://github.com/webpack/webpack/issues/1315#issuecomment-247269598
https://github.com/webpack/webpack/pull/2998

Categories