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

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',
}),

Related

Webpack 5 - mini-css-extract-plugin and split-chunks-plugin produces conflict on style.css

I am upgrading webpack on my application from v4 to v5. I am receiving this error on npx webpack:
[webpack-cli] Error: Conflict: Multiple chunks emit assets to the same filename style.css (chunks app and vendor)
at C:\workspace\my-lib\my-lib-ui\node_modules\webpack\lib\Compilation.js:4610:12
at C:\workspace\my-lib\my-lib-ui\node_modules\webpack\lib\Cache.js:91:34
at Array.<anonymous> (C:\workspace\my-lib\my-lib-ui\node_modules\webpack\lib\cache\MemoryCachePlugin.js:45:13)
at C:\workspace\my-lib\my-lib-ui\node_modules\webpack\lib\Cache.js:91:19
at Hook.eval [as callAsync] (eval at create (C:\workspace\my-lib\my-lib-ui\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:19:1)
at Cache.get (C:\workspace\my-lib\my-lib-ui\node_modules\webpack\lib\Cache.js:75:18)
at ItemCacheFacade.get (C:\workspace\my-lib\my-lib-ui\node_modules\webpack\lib\CacheFacade.js:111:15)
at C:\workspace\my-lib\my-lib-ui\node_modules\webpack\lib\Compilation.js:4556:22
at arrayEach (C:\workspace\my-lib\my-lib-ui\node_modules\neo-async\async.js:2405:9)
at Object.each (C:\workspace\my-lib\my-lib-ui\node_modules\neo-async\async.js:2846:9)
My webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin')
const MODE = process.env.NODE_ENV || 'development';
module.exports = {
entry: {
app: path.join(__dirname, 'src/main/js/index')
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
'react': path.resolve('./node_modules/react'),
'react-dom': path.resolve('./node_modules/react-dom')
}
},
output: {
path: path.resolve(__dirname, 'target/classes/public'),
filename: '[name].js',
assetModuleFilename: '[name]-[hash:7][ext]',
sourceMapFilename: '[name].js.map',
chunkFilename: '[name]-[hash:7].js'
},
mode: MODE,
module: {
rules: [
{
test: /\.(js|jsx)?$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
exclude: /node-modules/
}
}
},
{
test: /\.(css)$/,
use: [
MiniCssExtractPlugin.loader, 'css-loader'
]
},
{
test: /\.(scss)$/,
use: [
MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'
]
},
{
test: /\.(less)$/,
use: [
MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf|png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
}
]
},
plugins: [
new ESLintPlugin({extensions: ['js', 'jsx']}),
new MiniCssExtractPlugin({
filename: 'style.css'
}),
new CopyPlugin({
patterns: [{from: path.join(__dirname, 'node_modules/core-js/client/shim.min.js'), to: 'shim.js'}],
}),
],
optimization: {
chunkIds: 'named',
splitChunks: {
cacheGroups: {
vendor: {
filename: 'vendor.js',
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all'
},
default: false
}
},
},
devtool: MODE === 'development' ? 'inline-source-map' : false
};
and package.json:
"webpack": "^5.72.1",
"webpack-cli": "^4.9.2"
"mini-css-extract-plugin": "^2.6.0",
change filename: '[name].js', to filename: "[name].[contenthash].js"
Webpack is trying to split CSS files into chunks as well, but your MiniCssExtractPlugin is configured to output only one name filename: style.css. Change that to filename: [name].css. Don't forget to update your HTML template accordingly, as your root CSS file name will change.

Public assets is 404 on prod build (webpack)

I'm not really familiar with webpack and I have this issue where I can't access my assets on prod - it returns 404
I have this structure:
- repo
- public
- index.html
- images
- animals
- dog.png
- audio
- growl.mp3
- src
- index.js
... other files
Now on my index.js (or other files) I access the images by doing:
import { Loader, utils, Sprite, AnimatedSprite } from 'pixi.js'
loader
.add('images/animals/dog.png' )
.load(async () => {})
... other codes
And this works fine on local, but when I deploy on production It throws
Failed to load resource: the server responded with a status of 404 () - /images/animals/dog.png:1 Failed to load resource: the server responded with
My webpack looks like this:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CircularDependencyPlugin = require('circular-dependency-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
mode: isProd ? 'production' : 'development',
entry: './src/index.js',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/',
},
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
},
devtool: isProd ? 'cheap-module-eval-source-map' : 'source-map',
devServer: {
hot: true,
watchContentBase: true,
contentBase: [
path.resolve(__dirname, 'public'),
path.resolve(__dirname, 'build'),
],
publicPath: '/',
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
},
},
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new CircularDependencyPlugin({
exclude: /a\.js|node_modules/,
failOnError: false,
cwd: process.cwd(),
}),
new CopyWebpackPlugin([
{ from: 'public/audio', to: 'audio' },
{ from: 'public/images', to: 'images' },
]),
],
}
Ok, so I figured it out.
It turns out that I just need to make all publicPath to '' (empty string)

copy-webpack-plugin doesn't copy files

I try to just copy files to check simple webpack config. So I stuck trying to make copy-webpack-plugin to work - nothing happens: no copied files, no errors, nothing
Common config (webpack.common.js):
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const postCssPlugin = [
require('postcss-import'),
require('postcss-nested'),
require('postcss-simple-vars'),
require('autoprefixer')({
browsers: [
'last 3 versions',
'android 4.2'
]
})
];
module.exports = {
context: path.resolve(__dirname, '../src'),
entry: [
'babel-polyfill',
path.resolve(__dirname, '../src/index.js')
],
output: {
path: path.resolve(__dirname, '../dist/js'),
publicPath: '',
filename: 'app.js'
},
resolve: {
extensions: ['.jsx', '.js', '.json']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.p?css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: postCssPlugin
}
}
]
}
]
},
plugins: [
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../src/assets/**/*'),
to: path.resolve(__dirname, '../dist/assets'),
flatten: true
}
])
],
stats: {
modules: true,
warnings: false,
version: true,
timings: true,
performance: false,
hash: true,
errors: true,
errorDetails: true,
colors: true,
builtAt: true
}
};
webpack.prod.js:
const commonWebpackConfig = require('./webpack.common.js');
const UglifyJsWebpackPlugin = require('uglifyjs-webpack-plugin');
module.exports = Object.assign(commonWebpackConfig, {
mode: 'production',
plugins: [
new UglifyJsWebpackPlugin({
sourceMap: true
})
]
});
And build starting file build.js:
const webpack = require('webpack');
const webpackProdConfig = require('./webpack.config/webpack.prod.js');
webpack(webpackProdConfig, (err, stats) => {
if (err || stats.hasErrors()) {
console.error(err.stack || err);
}
console.log('Successfully compiled!');
});
So could anyone figure out why doesn't it work and where am I wrong?
copy-webpack-plugin: 4.5.2
node: 9.1.0
npm: 6.3.0
windows: 10
Addition - folder structure:
Try to copy from the dist folder. For me it worked
es.
new CopywebpackPlugin([{
from: path.resolve(__dirname, 'node_modules/mettrr-component-library/dist/img'),
to: path.resolve(__dirname, 'src/assets/img')
}]),

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 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