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

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
}

Related

Multiple assets emit different content to the same filename index.html

My webpack config gives the following error Multiple assets emit different content to the same filename index.html
when I delete the htmlWebpackPlugin it works, but I won't get any html to show. I'm using Vue.js and my config looks like this:
const path = require('path')
const { VueLoaderPlugin } = require('vue-loader')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = (env, argv) => ({
mode: argv && argv.mode || 'development',
devtool: (argv && argv.mode || 'development') === 'production' ? 'source-map' : 'eval',
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
node: false,
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
exclude: /\.module\.css$/
}
]
},
resolve: {
extensions: [
'.js',
'.vue',
'.json'
],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': path.resolve(__dirname, 'src')
}
},
plugins: [
new CleanWebpackPlugin({
cleanAfterEveryBuildPatterns: ['dist']
}),
new VueLoaderPlugin(),
new HtmlWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [{
from: path.resolve(__dirname, 'static'),
to: path.resolve(__dirname, 'dist'),
toType: 'dir'
}]
})
],
devServer: {
compress: true,
host: 'localhost',
https: true,
open: true,
overlay: true,
port: 9000
}
});
My file structure looks like this
I've looked at Conflict: Multiple assets emit to the same filename but no solution worked for me, are there any other options?
Could it be that Vue loader also emits index.html?
Try:
new HtmlWebpackPlugin({
template: './index.html',
filename: 'anotherFileName.html',
}),

WDS Live Reloading enabled twice

Idk why but all my code runs twice when I run webpack-dev-server(webpack serve)...
my folders path:
dist
src
js
app.js
loadBro.js
scss
main.scss
index.html
List item
here is my webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
app:'./src/js/app.js',
loadBro: './src/js/loadBro.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devtool: 'inline-source-map',
devServer:{
open:true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'src/index.html',
filename: 'index.html',
chunks: ['app', 'loadBro'],
}),
module: {
rules: [
{
test: /\.scss$/,
use: ['style-loader', 'css-loader','sass-loader']
},
],
},
};
you already applied plugins: [new HtmlWebpackPlugin({template: ...}) then no need add <script src="bundle whatever u give here"></script>

Webpack 4 - not minify css correctly and uglify js correctly

I have setup webpack for my project. I want to have css sources minified.
Here is the webpack.config.js:
var webpack = require('webpack');
const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
devtool: 'source-map',
mode: 'production',
entry: {
'target/web-resources/resources/lib/angular/angular.js': './node_modules/angular/angular.js',
'target/web-resources/resources/lib/angucomplete-alt/angucomplete-alt.js': './node_modules/angucomplete-alt/angucomplete-alt.js',
'target/web-resources/resources/lib/angucomplete-alt/angucomplete-alt.css': './node_modules/angucomplete-alt/angucomplete-alt.css',
},
module: {
rules: [
{
test: /\.css$/,
use: [
"style-loader",
"css-loader"
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.min\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorOptions: ['default', {discardComments: {removeAll: true}}],
canPrint: true
})
]
},
output: {
path: path.resolve(__dirname, '.'),
filename: '[name]'
}
};
However it produces me css file like: https://pastebin.com/rWWWvkGG (without expected extension .min.css - just .css)
Also orginal angucomplete-alt.js file which has 27kB it produces the file which is 167kB. It looks like it includes something more than orignal code: https://pastebin.com/E87pzTh0
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader, // <---- this is missing
"css-loader"
]
}
]
},

webpack is compile time is very slow

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.

How to dynamically load an asset (pdf) in an angular app using webpack?

I am trying to load a pdf into my angular app running on webpack dev server using HTML <object> tag with data attribute.
Since the pdf path is generated at run time and is absolute like C:\test.pdf.
It is not loaded into the UI but rather console logs the error -
Not allowed to load local resource: file:///C:/test.jpeg
However the production build of the app which doesn't run on hosting server but as static html works fine. Also, relative path works fine as well.
How can i load the pdf ?
webpack.common.js
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const rootDir = path.resolve(__dirname, '..');
module.exports = {
resolve: {
extensions: ['.js', '.ts'],
modules: [rootDir, path.join(rootDir, "node_modules")]
},
module: {
rules: [
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[ext]'
},
{
test: /\.(scss|css)$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader",
options: {
includePaths: ["node_modules/"]
}
}
]
}
]},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)#angular/,
path.resolve(__dirname, '../src')
)
]
};
webpack.dev.js
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
const path = require('path');
const rootDir = path.resolve(__dirname, '..');
commonConfig.entry = {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
};
commonConfig.module.rules.unshift({
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader', 'angular-router-loader']
});
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: path.resolve(rootDir, 'dist'),
publicPath: 'http://localhost:8080/',
filename: '[name].js',
chunkFilename: '[name].chunk.js'
},
plugins: [
new ExtractTextPlugin('[name].css')
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
});
You could tell the devServer from where to serve files.
devServer: {
historyApiFallback: true,
stats: 'minimal',
contentBase: ['./dist', 'C:\\']
}
Then you can load your file with <... src="/file_name.ext" ... />
But I would not recommend adding C:\ as contentBase. If you have the possiblity, define another output directory for your generated PDF.

Categories

Resources