webpack is compile time is very slow - javascript

My webpack is going very slow when it starts and when theres a change - compiling. Actually making development very slow right now. I'm only using greensock as the vendor but nothing else. I'm using only a few images too.. not sure.
Here is the code:
const path = require('path');
var webpack = require('webpack');
var htmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
// const ASSET_PATH = process.env.ASSET_PATH || '/'; ,
//publicPath: '/dist'
var isProd = process.env.NODE_ENV === 'production';
var cssDev = ['style-loader', 'css-loader', 'sass-loader'];
const VENDOR_LIBS =['gsap'];
var cssProd = ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader', 'sass-loader'
],
publicPath: '/dist'
});
var cssConfig = isProd ? cssProd : cssDev;
module.exports = {
entry: {
index: './src/js/index.js',
vendor: VENDOR_LIBS
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[hash].js'
},
devServer: {
//contentBase: path.join(__dirname, "/dist"),
compress: true,
port: 3000,
hot: true,
stats: "errors-only",
open: true
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all'
}
}
}
},
module:{
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.css$/,
use:[
"style-loader" , "css-loader"
]
},
{
test: /\.scss$/,
use: cssConfig
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: ['file-loader?name=[name].[ext]&outputPath=images/&publicPath=images/',
'image-webpack-loader'
]
},
{
test: /\.(eot|ttf|woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
use: 'file-loader?name=[name].[ext]&outputPath=fonts/&publicPath=fonts/'
}
]
},
plugins: [
new htmlWebpackPlugin({
title: '',
template: './src/index.html',
minify: {
collapseWhitespace: true
},
hash: true,
inject: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new ExtractTextPlugin({
filename: 'app.css',
disable: !isProd,
allChunks: true
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
]
};
Here is the package.json scripts:
"scripts": {
"killallProcesses": "killall node && webpack-dev-server",
"start": "webpack-dev-server",
"dev": "webpack -d",
"prod": "npm run clean && NODE_ENV=production webpack -p",
"clean": "rimraf ./dist/* ",
"deploy-gh": "npm run prod && git subtree push --prefix dist origin gh-pages"
}
So, not sure what is wrong here but compile time is very slow - using greensock as vendor but nothing else.. So not sure why its so slow. Even when I start webpack its brutal slow.

Webpack version 4 came with a huge speed imporvements.
First, use this strategy to split your config files for production and for development. Just follow the idea, don't follow the configurations because some of them are outdated.
Your config is the new config schema, based on webpack 4, só i'm going to do some tweaks to the basic one, and you can split them using the strategy i've linked.
First: install mini-css-extract-plugin.
const path = require('path');
const webpack = require('webpack');
const htmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isProd = process.env.NODE_ENV === 'production';
const cssDev = ['style-loader', 'css-loader', 'sass-loader'];
const cssProd = [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'];
const cssConfig = isProd ? cssProd : cssDev;
// content hash is better for production which helps increasing cache.
// contenthash is the hash generated given the content of the file, so this is going to change only if the content changed.
const outputFilename = isProd ? '[name].[contenthash].js' : 'name.[hash].js';
module.exports = {
entry: './src/js/index.js',
output: {
// dist folder is by default the output folder
filename: outputFilename
},
// this should go into the webpack.dev.js
devServer: {
//contentBase: path.join(__dirname, "/dist"),
compress: true,
port: 3000,
hot: true,
stats: "errors-only",
open: true
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
// this takes care of all the vendors in your files
// no need to add as an entrypoint.
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
module:{
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.css$/,
use:[MiniCssExtractPlugin.loader, 'css-loader']
},
{
test: /\.scss$/,
use: cssConfig
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: ['file-loader?name=[name].[ext]&outputPath=images/&publicPath=images/',
'image-webpack-loader'
]
},
{
test: /\.(eot|ttf|woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
use: 'file-loader?name=[name].[ext]&outputPath=fonts/&publicPath=fonts/'
}
]
},
plugins: [
new htmlWebpackPlugin({
title: '',
template: './src/index.html',
minify: {
collapseWhitespace: true
},
hash: true,
inject: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new MiniCssExtractPlugin({
filename: 'app.css',
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
]
};
Try this one and let me know what you got.

Related

Webpack 5 not showing images

I have a vue 3 app where I set up webpack 5 eventually. As I see I eliminated all my issues now the only thing remains is that it does not load my svg-s and images when I run the webpack serve script in dev mode. How can I configure webpack so that it would bundle my svg-s from the scr/assets folder?
my webpack config:
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');
const env = process.env.NODE_ENV || 'development';
const mode = process.env.VUE_APP_MODE || 'not-fullstack';
module.exports = {
mode: 'development',
entry: './src/main.js',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
},
resolve: {
alias: {
vue: '#vue/runtime-dom',
'#': path.join(__dirname, 'src'),
},
fallback: { crypto: false, stream: false },
},
module: {
rules: [
{
test: /\.vue$/,
use: [
{
loader: 'vue-loader',
},
],
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader', 'postcss-loader'],
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'images/[name].[hash].[ext]',
},
type: 'asset/resource',
},
{
test: /\.svg$/i,
use: [
{
loader: 'url-loader',
options: {
encoding: false,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, './public/index.html'),
}),
new VueLoaderPlugin(),
new CopyPlugin([
{ noErrorOnMissing: true, from: './src/assets', to: 'images' },
]),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env),
'process.env.VUE_APP_MODE': JSON.stringify(mode),
}),
],
devServer: {
historyApiFallback: true,
compress: true,
port: 3000,
},
};
And I reference my svg-s in my Vue component like this:
<img src="../../assets/logo.svg" alt="logo" />
As you can see I tried with the copy-webpack-plugin, maybe I just configured it wrong.
Thank you for your help in advance!
The config in webpack5 changed a lot
{
loader: 'url-loader',
options: {
encoding: false,
},
This is not working anymore. The url-loader is even removed from the npm packages.
The current way is found in the documentation
https://webpack.js.org/guides/asset-management/#loading-images

You are currently using minified code outside of NODE_ENV === 'production'

i created react app and i need to have 3 node_env:
"start": "cross-env NODE_ENV=development webpack serve",
"build-accept": "cross-env NODE_ENV=accept webpack",
"build-production": "cross-env NODE_ENV=production webpack"
When i deploy my app to accept environment, it says You are currently using minified code outside of NODE_ENV === 'production'. This means that you are running a slower development build of Redux
But i need this to run on accept mode. There are different api endpoints for accept and production.
How can i fix it?
Here's my webpack code:
const HtmlPlugin = require('html-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');
module.exports = {
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
publicPath: '/',
},
optimization: {
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
],
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
},
],
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
{
test: /\.s[ac]ss$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
],
},
plugins: [
new HtmlPlugin({
filename: 'index.html',
template: './public/index.html',
}),
new MiniCssExtractPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
}),
new CopyWebpackPlugin({
patterns: [
{ from: 'static' },
],
}),
// new BundleAnalyzerPlugin(),
],
};

Webpack: Issues with /src and /dist files because of the publicPath

When I run webpack-dev-server, with a publicPath of /dist, I'm able to see live-edits for my app (changes to html, styling, js). However, when I compile the app into a production build, the stylesheet and javascript load from /dist/main.css and /dist/main.js instead of from main.css and main.js
The problem seems to be with the publicPath setting. If I remove publicPath, the app compiles with main.css and main.js, but I'm not able to see live edits. However, if I keep publicPath: /dist I can see live edits, but now I get /dist/main.css and /dist/main.js
const path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/js/app.js',
output: {
filename: 'main.bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist'
}, //js output object
module: {
rules: [
{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
}, //sass to css
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['babel-preset-env']
}
}
]
} //babel
]
}, //module object
plugins: [
new MiniCssExtractPlugin({
filename: '[name].min.css',
chunkFilename: '[id].min.css'
}),
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
proxy: 'http://localhost:8080/dist'
}),
new HtmlWebpackPlugin({
template: './src/index.html',
/* minify: {
collapseWhitespace: true
}*/
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', {discardComments: {removeAll: true}}]
},
canPrint: true
})
] //plugins array
}

Webpack not outputting css file and fonts

I have a problem with my webpack congifuration. It runs without errors, but is not outputting any files other then app.js and index.html. Genetal styles are applied. Only thing that is not working is font
webpack ver ^3.5.6
extractTest ver ^3.0.0
const path = require('path');
const extractText = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const isProd = process.env.NODE_ENV === 'prod';
const cssDev = ['style-loader', 'css-loader', 'sass-loader'];
const cssProd = extractText.extract({
filename: 'styles.css',
fallback: 'style-loader',
use: 'css-loader!sass-loader',
publicPath: '/dist',
})
const cssConfig = isProd ? cssProd : cssDev;
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dev'),
filename: 'app.bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/, /__tests__/],
use: 'babel-loader'
},
{
test: /\.sass$/,
use: cssConfig
},
{
test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader'
}
]
},
devServer: {
historyApiFallback: true,
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000,
stats: 'errors-only'
},
plugins: [
new HtmlWebpackPlugin({
title: 'Recipes',
hash: true,
template: './src/index.ejs'
}),
new extractText('style.css'),
new webpack.HotModuleReplacementPlugin()
]
}

webpack dev server does not show the content

I have the following problem when running the webpack dev server:
when I run npm start, it show the following:
➜ directory git:(staging) ✗ npm start
directory #1.0.0 start directory
BUILD_DEV=1 BUILD_STAGING=1 ./node_modules/webpack-dev-server/bin/webpack-dev-server.js
http://localhost:8080/
webpack result is served from /undefined/
content is served from
directory
404s will fallback to /index.html
Hash: 75773622412153d5f921
Version: webpack 1.12.11
Time: 43330ms
I guess the problem might because the following line:
webpack result is served from /undefined/
When I open the browser at http://localhost:8080/, it appear as follow:
Cannot GET /
and there is no thing in the console.
Do you have any ideas for this problem ?
UPDATE: WEBPACK CONFIG FILE
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const deps = [
'moment/min/moment.min.js',
'underscore/underscore-min.js',
];
/* Include SASS path here if you want to this in your sass files:
* #import 'bourbon';
*/
const bourbon = require('node-bourbon').includePaths;
const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = path.resolve(__dirname);
const SASS_DEPS = [bourbon].toString();
const BUILD_NUMBER = process.env.CI_BUILD_NUMBER;
const common = {
entry: path.resolve(ROOT_PATH, 'app/index.js'),
output: {
filename: BUILD_NUMBER + '-[hash].js',
path: path.resolve(ROOT_PATH, 'build'),
publicPath: `/${BUILD_NUMBER}/`,
},
module: {
loaders: [
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass?includePaths[]=' + SASS_DEPS],
include: path.resolve(ROOT_PATH, 'app'),
},
{
test: /\.css$/,
loaders: [
'style',
'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'sass?includePaths[]=' + SASS_DEPS,
'postcss'
],
include: path.resolve(ROOT_PATH),
exclude: /(pure\/grids|Grids).*\.css$/,
},
{
test: /(pure\/grids|Grids).*\.css$/,
loaders: [
'style',
'css',
'sass?includePaths[]=' + SASS_DEPS,
],
include: path.resolve(ROOT_PATH),
},
{
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',
},
{
test: /\.json$/,
loader: 'json',
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'My App',
template: path.resolve(ROOT_PATH, 'app/index.html'),
inject: 'body',
minify: {
removeComments: true,
collapseWhitespace: true,
},
}),
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')),
__STAGING__: JSON.stringify(JSON.parse(process.env.BUILD_STAGING || 'false')),
__API_HOST__: JSON.stringify(process.env.BUILD_STAGING ? 'my.api' : 'my.api'),
}),
],
resolve: {
alias: {
'styles': path.resolve(ROOT_PATH, 'app/styles'),
},
extensions: ['', '.js', '.jsx', '.json'],
},
postcss: function() {
return [
require('postcss-import'),
require('autoprefixer'),
require('postcss-cssnext'),
]
}
};
if (TARGET === 'start' || !TARGET) {
module.exports = merge(common, {
output: {
filename: '[hash].js',
path: path.resolve(ROOT_PATH, 'build'),
publicPath: '/',
},
devtool: 'eval-source-map',
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: [
'react-hot',
'babel-loader'
],
include: path.resolve(ROOT_PATH, 'app'),
},
],
},
devServer: {
colors: true,
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
});
} else if (TARGET === 'build' || TARGET === 'builds') {
const config = {
resolve: {
alias: {},
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
include: path.resolve(ROOT_PATH, 'app'),
},
],
noParse: [],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compressor: {
screw_ie8: true,
warnings: false,
},
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'process.env': { 'NODE_ENV': JSON.stringify(process.env.NODE_ENV) },
}),
],
};
deps.forEach((dep) => {
const depPath = path.resolve(nodeModulesDir, dep);
config.resolve.alias[dep.split(path.sep)[0]] = depPath;
config.module.noParse.push(depPath);
});
module.exports = merge(common, config);
}
Same problem occurred to me when i started using babel-loader > 6.
It was fixed by adding contentBase in webpack dev server configuration.
In my case it looked like this
new WebPackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
contentBase: __dirname + '/public'
}).listen(3000, 'localhost')
I would be great to see your webpack config file to pin point the exact problem, but from the error message, there could be multiple problem
Make sure you are on the right port
Make sure your webpack config has
path and public path setup
Make sure you have contentBase setup as
well
Without seeing your webpack file and more concrete detail, it is quite hard to pinpoint the issue. But you can always go to https://webpack.github.io/docs/webpack-dev-server.html for information on how to set it up.

Categories

Resources