webpack 1 file-loader relative file path - javascript

I need to output the js, images, fonts, css to different directories. Webpack is configured accordingly and placing the files in the correct directories in the distribution directory:
/dist
/dist/images
/dist/css
/dist/js
/dist/fonts
I also had to extract the css file and for that reason, I notice that the file-loader option that is used to place the fonts and images into the right directory does not generated the correct url, so then the files fail to load in the web browser.
http://foobar.com/assets/css/main.css
http://foobar.com/assets/css/assets/images/foobar.png
When expected,
http://foobar.com/assets/images/foobar.png
The webpack config file follows:
var path = require("path");
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var config = require('./config');
var CompressionPlugin = require("compression-webpack-plugin");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: [
'./src/js/index.js'
],
output: {
path: __dirname + '/dist',
filename: 'assets/js/bundle-[hash].js'
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loaders: ['babel-loader'] },
{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style','css!sass') },
{ test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, loader: 'file-loader?name=[name].[ext]&publicPath=assets&outputPath=fonts' },
{ test: /\.(jpg|png|gif|svg)$/i, loader: 'file-loader?name=[name].[ext]&publicPath=assets&outputPath=images/'}
]
},
plugins: [
new ExtractTextPlugin("assets/css/[name].css"),
new HtmlWebpackPlugin({
inject: true,
template: __dirname + '/src/' + 'index.html',
filename: 'index.html'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production'),
'PORT_NODE_SERVER': config.port.node_server_prod_port
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: true
}
}),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: true,
compress: {
warnings: false, // Suppress uglification warnings
pure_getters: true,
unsafe: true,
unsafe_comps: true,
screw_ie8: true
},
output: {
comments: false,
},
exclude: [/\.min\.js$/gi] // skip pre-minified libs
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
})
]
};

I found a solution. It seems that webpack v1 needs a hint about the base path to be able to solve this, for that reason the full base path is required, has follow:
var path = require("path");
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var config = require('./config');
var CompressionPlugin = require("compression-webpack-plugin");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: [
'./src/js/index.js'
],
output: {
path: __dirname + '/dist',
filename: 'js/bundle-[hash].js',
publicPath: '/myapp/assets'
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loaders: ['babel-loader'] },
{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style','css!sass') },
{ test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, loader: 'file-loader?name=/fonts/[name].[ext]' },
{ test: /\.(jpg|png|gif|svg)$/i, loader: 'file-loader?name=/images/[name].[ext]'}
]
},
plugins: [
new ExtractTextPlugin("css/[name]-[hash].min.css"),
new HtmlWebpackPlugin({
inject: true,
template: __dirname + '/src/' + 'index.html',
filename: 'index.html'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production'),
'PORT_NODE_SERVER': config.port.node_server_prod_port
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: true
}
}),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: true,
compress: {
warnings: false, // Suppress uglification warnings
pure_getters: true,
unsafe: true,
unsafe_comps: true,
screw_ie8: true
},
output: {
comments: false,
},
exclude: [/\.min\.js$/gi] // skip pre-minified libs
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
})
]
};
About the /myapp has in http://foobar.com/myapp and then http://foobar.com/myapp/assets/js/bundle-438348934.js and so http://foobar.com/myapp/assets/fonts/myfont.woff
Hope this helps!

Related

adding directory with webpack

I decided to give webpack a shot and am using a starter kit for a small project. I'm not sure where I am going wrong but I want to add a new directory of files and access them like any other build.In this case it is the folder "particles.js-master". When I add a directory I cannot seem to access anything in the folder. I'm assuming I have to add an output or the like to the webpack config? Any advice would be greatly appreciated, thanks :)
here is my project structure
webpack:
const path = require('path');
const webpack = require('webpack');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const CssUrlRelativePlugin = require('css-url-relative-plugin');
const glob = require('glob');
const IS_DEV = process.env.NODE_ENV === 'dev';
const config = {
mode: IS_DEV ? 'development' : 'production',
devtool: IS_DEV ? 'eval' : 'source-map',
entry: './src/js/index.js',
output: {
filename: 'js/[name].[hash].js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: IS_DEV,
},
},
'css-loader',
'sass-loader',
],
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: '[name].[ext]',
fallback: 'file-loader',
outputPath: 'public/images',
},
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65,
},
pngquant: {
quality: '65-90',
speed: 4,
},
gifsicle: {
interlaced: false,
},
webp: {
quality: 75,
},
},
},
],
},
],
},
plugins: [
new CleanWebpackPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'windows.jQuery': 'jquery',
}),
new CopyWebpackPlugin([
{
from: './src/public',
to: 'public',
},
]),
new MiniCssExtractPlugin({
filename: IS_DEV ? 'css/[name].css' : 'css/[name].[contenthash].css',
chunkFilename: 'css/[id].css',
}),
new webpack.HashedModuleIdsPlugin(),
new PreloadWebpackPlugin({
include: 'initial',
}),
new CssUrlRelativePlugin(),
],
devServer: {
contentBase: path.join(__dirname, 'src'),
},
optimization: {
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
vendor: {
test: /node_modules/,
chunks: 'initial',
name: 'vendor',
priority: 10,
enforce: true,
},
},
},
minimizer: [],
},
};
if (!IS_DEV) {
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
config.optimization.minimizer.push(
new TerserPlugin(),
new OptimizeCSSAssetsPlugin({})
);
}
const files = glob.sync('./src/*.html');
files.forEach(file => {
config.plugins.push(
new HtmlWebPackPlugin({
filename: path.basename(file),
template: file,
favicon: path.resolve(__dirname, './src/public/icon.ico'),
minify: !IS_DEV,
})
);
});
module.exports = config;

How to load Highcharts using Webpack

I'm using Highcharts lib component of V5.0.10
highcharts.min.js
highcharts.more.min.js
highcharts.prototype-adapter.min.js
and I'm importing them in my lib.js which is entry point for webpack.config.js
require('../customLibs/highcharts/js/highcharts.min.js');
require('../customLibs/highcharts/js/highcharts.more.min.js');
require('../customLibs/highcharts/js/highcharts.prototype-adapter.min.js');
Here is my Webpack.config.js
var path = require('path');
var webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = {
entry: [
'angular',
'./src/lib.js',
'./src/app.js'
],
output: {
path: path.join(__dirname, 'mcdist'),
filename: '[name].js',
},
module: {
rules: [{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader?name=[name].[ext]&outputPath=images/',
}, {
test: /\.css|scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ['css-loader', "sass-loader"]
})
}, {
test: /\.html$/,
exclude: [
path.join(__dirname, '/src/index.html')
],
use: [
{ loader: 'ngtemplate-loader?relativeTo=' + (path.resolve(__dirname, './src')) },
{ loader: 'html-loader' },
]
}],
},
plugins: [
new HtmlWebpackPlugin({
title: 'Demo',
minify: {
collapseWhitespace: true,
},
cache: true,
hash: true,
inject: true,
filename: './index.html',
template: 'src/index.html'
}),
new ExtractTextPlugin({
filename: "app.css",
disable: false,
allChunks: true
}),
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
Holder: 'holderjs',
moment: 'moment',
loadash: 'loadash.min',
})
],
devServer: {
proxy: [{
context: [
'/mcdist/api',
'/mcdist/appConfig',
'/mcdist/logout',
'/mcaid/j_spring_security_logout'
],
target: 'http://localhost:8080',
secure: false
}],
port: 9000
},
};
module.exports = config;
but I'm getting 'ReferenceError: Highcharts is not defined' when JS file referring to Highcharts loads up.
Can you please suggest correct way to load Highcharts with Webpack and load them in application to use ?

Syntax error when webpack build for development

I can't build a project with webpack because I'm getting a syntax error all the time.
Moreover when my friend runs the same code on Linux (I work on Windows 10) he doesn't get any errors and everything works fine.
Here is my webpack config
const path = require('path');
const autoprefixer = require('autoprefixer');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const HMRPlugin = require('webpack/lib/HotModuleReplacementPlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const OccurrenceOrderPlugin = require('webpack/lib/optimize/OccurrenceOrderPlugin');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
//=========================================================
// VARS
//---------------------------------------------------------
const NODE_ENV = process.env.NODE_ENV;
const DEVELOPMENT = NODE_ENV === 'development';
const PRODUCTION = NODE_ENV === 'production';
const HOST = process.env.HOST || '127.0.0.1';
const PORT = process.env.PORT || '3000';
//=========================================================
// LOADERS
//---------------------------------------------------------
const rules = {
js: {
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
json: {
test: /\.json$/,
loader: 'json-loader',
},
css: {
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'resolve-url-loader', 'postcss-loader'],
}),
},
scss: {
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'resolve-url-loader', 'postcss-loader', 'sass-loader'],
}),
},
fonts: {
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader',
query: {
name: `[name].[ext]`,
publicPath: '/assets/fonts/',
}
},
images: {
test: /\.(svg|png|jpg|jpeg|gif)$/,
loader: 'file-loader',
query: {
limit: 10000,
name: `[name].[ext]`,
publicPath: '/assets/images/',
}
}
};
//=========================================================
// CONFIG
//---------------------------------------------------------
const config = {};
config.entry = {
polyfills: './src/application/polyfills.js',
main: ['./src/application/index.js'],
};
config.output = {
filename: 'assets/js/[name].js',
path: path.resolve('./dist'),
// publicPath: '/',
};
config.resolve = {
extensions: ['.js', '.json'],
modules: [
path.resolve('./src'),
'node_modules',
]
};
config.module = {
rules: [
rules.js,
rules.css,
rules.json,
rules.scss,
rules.fonts,
rules.images,
]
};
config.plugins = [
new LoaderOptionsPlugin({
debug: !PRODUCTION,
cache: !PRODUCTION,
minimize: PRODUCTION,
options: {
postcss: [
autoprefixer({
browsers: ['last 3 versions'],
})
],
sassLoader: {
outputStyle: PRODUCTION ? 'compressed' : 'expanded',
precision: 10,
sourceComments: false,
sourceMap: PRODUCTION,
}
}
}),
new DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
}),
new OccurrenceOrderPlugin(true),
new NamedModulesPlugin(),
new CommonsChunkPlugin({
name: 'polyfills',
chunks: ['polyfills'],
}),
// This enables tree shaking of the vendors modules
new CommonsChunkPlugin({
name: 'vendor',
chunks: ['main'],
minChunks: module => /node_modules/.test(module.resource),
}),
new CommonsChunkPlugin({
name: ['polyfills', 'vendor'].reverse(),
}),
new CopyWebpackPlugin([
{
from: './src/assets',
to: 'assets',
ignore: ['**/*.scss'],
}
]),
new ExtractTextPlugin({
filename: 'assets/css/[name].css',
disable: !PRODUCTION,
allChunks: true,
}),
new HtmlWebpackPlugin({
filename: 'index.html',
hash: false,
inject: 'body',
chunksSortMode: 'dependency',
template: './src/index.html',
})
];
//=====================================
// DEVELOPMENT
//-------------------------------------
if (DEVELOPMENT) {
config.devtool = 'cheap-module-source-map';
config.entry.main.unshift(
'react-hot-loader/patch',
`webpack-dev-server/client?http://${HOST}:${PORT}`,
'webpack/hot/only-dev-server',
);
config.plugins.push(
new HMRPlugin(),
new ProgressPlugin(),
);
config.devServer = {
contentBase: path.resolve(__dirname, 'dist'),
historyApiFallback: true,
host: HOST,
hot: true,
port: PORT,
stats: {
cached: true,
cachedAssets: true,
children: false,
chunks: false,
chunkModules: false,
colors: true,
modules: false,
hash: false,
reasons: true,
timings: true,
version: false,
}
};
}
//=====================================
// PRODUCTION
//-------------------------------------
if (PRODUCTION) {
config.devtool = 'hidden-source-map';
config.plugins.push(
new WebpackMd5Hash(),
new UglifyJsPlugin({
comments: false,
compress: {
unused: true,
dead_code: true,
screw_ie8: true,
warnings: false,
},
mangle: {
screw_ie8: true,
}
})
);
}
module.exports = config;
And this is my package.json scripts
"scripts": {
"test": "jest",
"server:dev": "set NODE_ENV='development' && webpack-dev-server --color",
"start": "npm run server:dev",
"build": "set NODE_ENV='production' && webpack --color"
},
When I try to run "npm start", I have this error
C:\Users\vellgreen\Desktop\my_webpack_react\webpack.config.js:184
);
^
SyntaxError: Unexpected token )
when I put this into comment everything is working normal.
config.entry.main.unshift(
'react-hot-loader/patch',
`webpack-dev-server/client?http://${HOST}:${PORT}`,
'webpack/hot/only-dev-server',
);
config.plugins.push(
new HMRPlugin(),
new ProgressPlugin(),
);
When I run code for production everything is also fine.
My OS is Windows 10, webpack v3.1.0, npm v5.3.0, node v6.10.3.
Does anyone know what may cause such an error?
Trailing commas in functions are a relatively recent feature and Node started supporting it in version 8. Your friend is simply using a version that supports it (it's unrelated to the OS).
config.entry.main.unshift(
'react-hot-loader/patch',
`webpack-dev-server/client?http://${HOST}:${PORT}`,
'webpack/hot/only-dev-server',
// ^ --- remove this comma
);
config.plugins.push(
new HMRPlugin(),
new ProgressPlugin(),
// ^ --- and this comma
);

webpack 3 long term caching not work

I'm attempting to use webpack v3 to test long term caching. When I build twice by webpack(just make a change to index.jsx file), and the hash value changed to vendor file.
webpack.config.js
Reference:Caching
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin')
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin')
const InlineChunkManifestHtmlWebpackPlugin = require('inline-chunk-manifest-html-webpack-plugin')
// const CompressionPlugin = require('compression-webpack-plugin')
/**
* global variable of config
*/
// replace localhost with 0.0.0.0 if you want to access
// your app from wifi or a virtual machine
const host = process.env.HOST || '0.0.0.0'
const port = process.env.PORT || 8080
const allowedHosts = ['192.168.19.61']
const sourcePath = path.join(__dirname, './site')
const distPath = path.join(__dirname, './dist')
const htmlTemplate = './index.template.ejs'
const stats = {
assets: true,
children: false,
chunks: false,
hash: false,
modules: false,
publicPath: false,
timings: true,
version: false,
warnings: true,
colors: {
green: '\u001b[32m'
}
}
/**
* webpack config
*/
module.exports = function (env) {
const nodeEnv = env && env.production ? 'production' : 'development'
const isProd = nodeEnv === 'production'
/**
* Mete Design Webpack V3.1 Buiding Informations
*/
console.log('--------------Mete Design Webpack V3.1--------------')
console.log('enviroment:' + nodeEnv)
console.log('host:' + host)
console.log('port:' + port)
console.log('dist path:' + distPath)
console.log('platform:' + env.platform)
console.log('-----------------Mete Design Group------------------')
/**
* common plugin
*/
const plugins = [
new webpack.optimize.CommonsChunkPlugin({
// vendor chunk
names: ['manifest', 'vendor'] // the name of bundle
}), // new webpack.optimize.CommonsChunkPlugin({ // name: 'manifest', // minChunks: Infinity // }), // setting production environment will strip out // some of the development code from the app // and libraries
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv)
}
}), // create css bundle // allChunks set true is for code splitting
new ExtractTextPlugin({
filename: 'css/[name]-[contenthash].css',
allChunks: true
}), // create index.html
new HtmlWebpackPlugin({
template: htmlTemplate,
inject: true,
production: isProd,
minify: isProd && {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
}),
new InlineManifestWebpackPlugin({
name: 'webpackManifest'
}),
new InlineChunkManifestHtmlWebpackPlugin({
manifestPlugins: [
new ChunkManifestPlugin({
filename: 'manifest.json',
manifestVariable: 'webpackManifest',
inlineManifest: false
})
]
})
]
if (isProd) {
/**
* production envrioment plugin
*/
plugins.push(
// minify remove some of the dead code
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true
},
mangle: false
}),
new webpack.optimize.ModuleConcatenationPlugin())
} else {
/**
* development enviroment plugin
*/
plugins.push(
// make hot reloading work
new webpack.HotModuleReplacementPlugin(),
// show module names instead of numbers in webpack stats
new webpack.NamedModulesPlugin(),
// don't spit out any errors in compiled assets
new webpack.NoEmitOnErrorsPlugin()
// load DLL files
// new webpack.DllReferencePlugin({context: __dirname, manifest: require('./dll/react_manifest.json')}),
// new webpack.DllReferencePlugin({context: __dirname, manifest: require('./dll/react_dom_manifest.json')}),
// // make DLL assets available for the app to download
// new AddAssetHtmlPlugin([
// { filepath: require.resolve('./dll/react.dll.js') },
// { filepath: require.resolve('./dll/react_dom.dll.js') }
// ])
)
}
return {
devtool: isProd ? 'source-map' : 'cheap-module-source-map',
entry: {
main: ['babel-polyfill', path.join(sourcePath, 'index.js')],
// static lib
vendor: ['react', 'react-dom', 'react-router-dom']
},
output: {
filename: isProd ? 'js/[name]-[hash].bundle.js' : 'js/[name].bundle.js',
chunkFilename: isProd ? 'js/[id]-[chunkhash].bundle.js' : 'js/[id].bundle.js',
path: distPath,
publicPath: './'
},
// loader
module: {
rules: [
// js or jsx loader
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: [['es2015', {
'modules': false
}], 'react', 'stage-0'],
cacheDirectory: true // Since babel-plugin-transform-runtime includes a polyfill that includes a custom regenerator runtime and core.js, the following usual shimming method using webpack.ProvidePlugin will not work:
}
}
}, // css loader
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [{
loader: 'css-loader',
options: {
minimize: isProd
}
}],
publicPath: '/'
})
}, // scss loader
/* {
test: /\.scss$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
publicPath: '/',
fallback: 'style-loader',
use: [
// {loader: 'autoprefixer-loader'},
{
loader: 'css-loader',
options: {
minimize: isProd
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
includePaths: [sourcePath, path.join(__dirname, './src')]
}
}
]
})
}, */
// images loader
{
test: /\.(png|svg|jpg|gif)$/,
loader: 'url-loader?limit=8024&name=assets/images/[name]-[hash].[ext]'
},
{
test: /\.(woff2?|otf|eot|ttf)$/i,
loader: 'url-loader?limit=8024&name=assets/fonts/[name].[ext]',
options: {
publicPath: distPath
}
},
{
test: /\.md$/,
loader: 'raw-loader'
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [path.resolve(__dirname, 'node_modules'), sourcePath],
alias: {
md_components: path.resolve(__dirname, 'src/components'),
md_midware: path.resolve(__dirname, 'src/md-midware')
}
},
plugins,
stats,
// webpack dev server
devServer: {
// 文件路劲,一般静态文件需要
contentBase: '/',
// 是否启用gzip压缩
compress: true,
// 是否启用热替换
hot: true,
port,
// 开启任意ip访问
host,
// 允许列表中host访问
allowedHosts,
// 取消host列表安全检查,开发环境启用,默认关闭,开启则allowedHosts无效
// disableHostCheck: true,
// 关闭webpack重启打包信息,错误和警告仍然会显示
noInfo: true,
// 浏览器全屏显示编译器错误信息
overlay: true,
// 公共文件,浏览器可直接访问,HMR必须
publicPath: '/'
}
}
}
fisrt build
js/vendor-a674cd02275fdf4760bd.bundle.js 343 kB 1 [emitted] [big] vendor
second build(just update index.jsx)
js/vendor-f8d5fc2097878041c158.bundle.js 343 kB 1 [emitted] [big] vendor
Both hashes change even though I only updated the index file.
Help
Anyone can help me to check this problem? Thanks.
Github Repo:webpack_long_term_cache_test
filename in output use chunkhash, and reset the CommonsChunkPlugin name: ['vendor', 'manifest']

In production Webpack 2.2.0.rc-0 will uglify/minify vendor.js and manifest.js but not bundle.js

I'm trying to figure out why my vendor and manifest files are minified and uglified but my bundle is not. Could it be the order of the plugins? Maybe something to do with the CommonsChunkPlugin?
This is my UglifyJsPlugin code:
new webpack.optimize.UglifyJsPlugin({
debug: false,
minimize: true,
sourceMap: false,
output: {
comments: false
},
compressor: { // eslint-disable-line camelcase
warnings: false,
unused: true,
dead_code: true
},
mangle: false
}),
and this is my webpack config object a whole:
const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');
const del = require('del');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const pkg = require('../package.json');
const autoprefixer = require('autoprefixer');
module.exports = {
entry: {
bundle: `./${conf.path.src('index')}`,
vendor: `./src/app/dependencies`,
},
output: {
path: path.join(process.cwd(), conf.paths.dist),
filename: '[name].[chunkhash].js'
},
module: {
rules: [
{
test: /.json$/,
use: ['json-loader']
},
{
test: /.ts$/,
exclude: /node_modules/,
enforce: 'pre',
use: ['tslint-loader']
},
{
test: /\.(css|scss)$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
'postcss-loader'
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'ng-annotate-loader',
'babel-loader'
]
},
{
test: /\.ts$/,
exclude: /node_modules/,
use: ['ts-loader']
},
{
test: /.html$/,
use: ['html-loader']
},
{
test: /\.(jade|pug)$/,
use: ['pug-html-loader']
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
use: ['url-loader?limit=30000&name=[name]-[hash].[ext]']
},
{
test: /\.less$/,
use: ['style-loader','css-loader', 'less-loader']
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
debug: false,
minimize: true,
sourceMap: false,
output: {
comments: false
},
compressor: { // eslint-disable-line camelcase
warnings: false,
unused: true,
dead_code: true
},
mangle: false
}),
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest']
}),
new webpack.optimize.OccurrenceOrderPlugin(),
// new webpack.NoErrorsPlugin(), // emits no scripts to browser if there are any errors at all
new HtmlWebpackPlugin({
template: conf.path.src('index.html'),
inject: true
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
conf.paths.src
),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new ExtractTextPlugin('index-[contenthash].css'),
new webpack.LoaderOptionsPlugin({
options: {
postcss: () => [autoprefixer],
resolve: {},
ts: {
configFileName: 'tsconfig.json'
},
tslint: {
configuration: require('../tslint.json')
}
}
}),
new CopyWebpackPlugin([{
from: path.join(conf.paths.src, 'integration', 'embedder', 'embedder.js'),
to: path.join('integration', 'embedder', 'embedder.js')
}])
],
resolve: {
extensions: [
'.webpack.js',
'.web.js',
'.js',
'.ts'
]
}
};
turns out the answer was to add an options config to the babel-loader to include presets es2015 as so:
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'ng-annotate-loader'
},
{
loader: 'babel-loader',
options: {
presets: ['es2015'],
}
}
]
},
This is needed for uglify/minifying es6 code with webpack 2.

Categories