Error in conflict multiple assets emit different content to the same filename index html

if I create a new vue.js project on my macbook and compile it with "npm run serve", I get the following error. I haven't changed any file since creating it. markus@Markuss-MBP meinerstesprojekt % ...

if I create a new vue.js project on my macbook and compile it with «npm run serve», I get the following error.
I haven’t changed any file since creating it.

markus@Markuss-MBP meinerstesprojekt % npm run serve

> meinerstesprojekt@0.1.0 serve
> vue-cli-service serve

 INFO  Starting development server...


 ERROR  Failed to compile with 1 error                                                                                                                                    6:12:51 PM

 error  

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

ERROR in Conflict: Multiple assets emit different content to the same filename index.html

webpack compiled with 1 error

vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true
})

module.exports = {
chainWebpack: (config) => {
config.resolve.symlinks(true)
}
}

package.json

{
  "name": "meinerstesprojekt",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.8.3",
    "vue": "^2.6.14"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-service": "^5.0.1",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "vue-template-compiler": "^2.6.14"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

npm version: 8.5.3
Node-Version: v16.14.0
Vue-Version: @vue/cli 5.0.1

The following folders are in the path:

├── README.md
├── babel.config.js
├── dist
├── jsconfig.json
├── node_modules
├── package-lock.json
├── package.json
├── public
├── src
└── vue.config.js

Do you know why this doesn’t work? Unfortunately, I couldn’t find the solution by searching the web

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

donotlb opened this issue

Sep 25, 2019

· 18 comments

Comments

@donotlb

Bug report

What is the current behavior?

webpack shows a warning when rebuild:

Multiple assets emit different content to the same filename app.js.map

If the current behavior is a bug, please provide the steps to reproduce.

webpack.config.js

const path = require('path')
const webpack = require('webpack')

module.exports = {
  mode: 'development',
  entry: {
    app: './entry.js'
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: '[name].js'
  },
  devtool: false,
  plugins: [
    new webpack.SourceMapDevToolPlugin({
      filename: '[name].js.map'
    }),

    new webpack.HotModuleReplacementPlugin() // !!!!!!! remove this line, the warning will not display
  ]
}

entry.js

console.log(`
  modify this module, then webpack shows warning:
  WARNING in Conflict: Multiple assets emit different content to the same filename app.js.map
`)

reproduction steps:

  1. use SourceMapDevToolPlugin and HotModuleReplacementPlugin (refer to webpack.config.js)
  2. npx webpack --watch
  3. modify content of entry.js, then save
  4. webpack shows a warning: Multiple assets emit different content to the same filename app.js.map

webpack doesn’t show this warning if i remove the line new webpack.HotModuleReplacementPlugin()

What is the expected behavior?

webpack should not show a warning

Other relevant information:
webpack version: 4.41.0
Node.js version: v10.15.3
Operating System: win10

FranckFreiburger, DLCnow, dubrovsky-kiril, branchard, ad0ran, kuitos, matthewfavorliu, levenleven, mvshvets, mufasa71, and 2 more reacted with eyes emoji

@mvshvets

I have the same warning. I am using devServer and webpack.SourceMapDevToolPlugin. The file names are static.

@alexander-akait

Please create a reproducible test repo

@donotlb

@alexander-akait

@alexander-akait

@donotlb Please use filename: '[file].map[query]' for SourceMapDevToolPlugin, you can’t use [name] because hmr emit updates for example using app.3d0af954e7d8c1e90af5.hot-update.js file and you have three assets before generating source maps:

  • 3d0af954e7d8c1e90af5.hot-update.json
  • app.js — [name] is app
  • app.3d0af954e7d8c1e90af5.hot-update.js — [name] is app

then you generate source maps using [name].js.map for second asset and third asset you get two source maps with the same name app.js.map

dev-geddy, JSoon, jruuttun, ondrej-111, sergeybe, xavier-zyc, mufasa71, pitops, jjarcik, optimify-team, and 23 more reacted with thumbs up emoji
RolandWarburton, kuanyshjoinedlane, optimify-team, JamesRosenthal, vp8x8, BrightLin, and crucialfelix reacted with hooray emoji
khelkun and nklapnsk reacted with confused emoji
donotlb, optimify-team, JamesRosenthal, LinseyKarter, vp8x8, lesleyandreza, jhemarcos, and BrightLin reacted with heart emoji
BrightLin and nklapnsk reacted with rocket emoji

@alexander-akait

The problem is resolved, feel free to feedback, thanks for issue

@Shelmy-pp

Please help to solve this warnings after angular 9 and primeng 9 migration

WARNING in ./src/assets/css/style.css
Module Warning (from ./node_modules/postcss-loader/src/index.js):
Warning

(146:3) start value has mixed support, consider using flex-start instead

WARNING in Conflict: Multiple assets emit different content to the same filename loading.gif

WARNING in Conflict: Multiple assets emit different content to the same filename password-meter.png

mohanramphp, TENEr98, hbweb, khasky, calcifer9000, admin-learnseeker, vigneshpushkaranHMCTS, and JJack27 reacted with thumbs up emoji
mohanramphp, admin-learnseeker, richardrich991, lyczos, and mattrwalters reacted with eyes emoji

@MartinsOnuoha

If you’re facing this problem with Quasar, be sure to set gzip to false in quasar.conf.js within the build object.

@Sacramentix

If you’re facing this problem with Quasar, be sure to set gzip to false in quasar.conf.js within the build object.

Thanks !

@kerasus

If you’re facing this problem with Quasar, be sure to set gzip to false in quasar.conf.js within the build object.

in quasar i need gzip: true
so this work for me:

in quasar.conf.js

chainWebpack (chain) {
      const hashh = '[id].[name].[chunkhash]'
      chain.output.filename('js/[name]/'+hashh+'.bundle.js')
      chain.output.chunkFilename('js/[name]/'+hashh+'.chunk.js')
      chain.plugin('eslint-webpack-plugin')
        .use(ESLintPlugin, [{ extensions: [ 'js', 'vue' ] }])
 }

@Grawl

For me using Quasar v1 this problem caused because I placed different images with same name in different folders, and then I import them.

Files tree:

- foo
	- index.ts
	- assets
		-  image.png
 - bar
	- index.ts
	- assets
		-  image.png

foo/index.ts:

import image from './assets/image.png`

bar/index.ts:

import image from './assets/image.png`

And then I get error in build console when I run quasar dev:

Error: Conflict: Multiple assets emit different content to the same filename img/image.png

But I do not get this error when I run quasar build.

It’s because Webpack config in Quasar uses image hash only on build mode, not dev.

When I look into this image in browser, it’s /img/image.png for both images from both folders. But I don’t want to name images differently since they in different folders already, and I cannot guarantee that every image in my project have unique name.

So I added this to quasar.conf.js:

chainWebpack(chain) {
	chain.module.rule('images')
		.use('url-loader')
		.loader('url-loader')
		.options({ esModule: false, limit: 0, name: 'img/[hash].[ext]' })
},

Now every image has hash in filename.

deeeki

added a commit
to deeeki/rails_jsbundling_webpack
that referenced
this issue

Mar 8, 2022

@deeeki

@Haixing-Hu

@Grawl you saved me a lot of time 👏🏻

@BrightLin

This work for me. Thanks !

new webpack.SourceMapDevToolPlugin({
  filename: "[file].map[query]", 
}),

@donotlb Please use filename: '[file].map[query]' for SourceMapDevToolPlugin, you can’t use [name] because hmr emit updates for example using app.3d0af954e7d8c1e90af5.hot-update.js file and you have three assets before generating source maps:

  • 3d0af954e7d8c1e90af5.hot-update.json
  • app.js — [name] is app
  • app.3d0af954e7d8c1e90af5.hot-update.js — [name] is app

then you generate source maps using [name].js.map for second asset and third asset you get two source maps with the same name app.js.map

@khelkun

@alexander-akait
Sorry to bother you but I don’t understand what’s going on here. I had this simple config in a webpack 3 project:

const path = require('path')
const webpack = require('webpack')

module.exports = {
  mode: 'development',
  entry: {
    app: './entry.js'
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: '[name].js',
    sourceMapFilename: '[name].js.map'
  },
  devtool: 'source-map'
}

After upgrading to webpack 5, I encountered the error mentionned in this issue:

Multiple assets emit different content to the same filename app.js.map

Commenting sourceMapFilename config solves the issue. The app.3d0af954e7d8c1e90af5.hot-update.js was not existing in webpack 3?

@alexander-akait

Do you update webpack-dev-server, and why don’t use the default '[file].map[query]' value for sourceMapFilename? Try to add [query]

@khelkun

Do you update webpack-dev-server,
Yes I did:

    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.0",
    "webpack-dev-server": "^4.11.1"

why don’t use the default '[file].map[query]' value for sourceMapFilename?

Considering I commented the sourceMapFilename config line, I guess I do use the default value for sourceMapFilename. There was no relevant reason for me to not use the default sourceMapFilename in my previous config.
If I set sourceMapFilename : '[file].map[query]', I obtain the same build output after webpack --mode=production.

@mlisowsk

@alexander-akait Hi Alexander, I think it would be helpful if the documentation at https://webpack.js.org/plugins/source-map-dev-tool-plugin/ could be updated to remind users of using correct sourceMapFilename.

Specifically the examples there use '[name].js.map' which is likely why so many people make this mistake. (The example may work due to its simplicity, but you know our first attempt is copy & paste the example ;-) )

@alexander-akait

Содержание

  1. Vue version 5.0.1. After downloading, run NPM run serve to report an error #7043
  2. Comments
  3. Version
  4. Environment info
  5. Steps to reproduce
  6. What is expected?
  7. What is actually happening?
  8. Footer
  9. Vue version 5.0.1. After downloading, run NPM run serve to report an error #7043
  10. Comments
  11. Version
  12. Environment info
  13. Steps to reproduce
  14. What is expected?
  15. What is actually happening?
  16. Footer
  17. WARNING in Conflict: Multiple assets emit different content to the same filename 3rdpartylicenses.txt #16193
  18. Comments
  19. Command (mark with an x )
  20. Is this a regression?
  21. Description
  22. 🔬 Minimal Reproduction
  23. 🔥 Exception or Error
  24. 🌍 Your Environment
  25. Error: Conflict: Multiple chunks emit assets to the same filename ssr-bundle.js #29
  26. Comments
  27. Конфликт: несколько ресурсов отправляются в одно и то же имя файла

Vue version 5.0.1. After downloading, run NPM run serve to report an error #7043

Version

Environment info

Steps to reproduce

Follow the normal installation steps, and then report an error when running NPM run serve:
Conflict: Multiple assets emit different content to the same filename index. html
ERROR in Conflict: Multiple assets emit different content to the same filename index. html
webpack compiled with 1 error

What is expected?

How to solve it?

What is actually happening?

Conflict: Multiple assets emit different content to the same filename index.html
ERROR in Conflict: Multiple assets emit different content to the same filename index.html
webpack compiled with 1 error

The text was updated successfully, but these errors were encountered:

Have you solved the problem?
问题解决了吗?

Same problem with @vue/cli 5.0.1, Node v14.17.5, vue 3.2.13, and npm 7.20.6

Edit: Downgraded to @vue/cli 4.5.15, works now

Same problem with @vue/cli 5.0.1, Node v14.17.5, vue 3.2.13, and npm 7.20.6

Edit: Downgraded to @vue/cli 4.5.15, works now

it works. thank you.

May be your project path has a special symbol like ‘(‘ or ‘)’. I’m not sure if it’s a bug of copy-webpack-plugin or fast-glob, because cli will add the absolute path of the index.html in the public folder to the ignore list, if the path has a special symbol, copy-webpack-plugin will not match the path and will not ignore it. Therefore index.html will emit twice. You can rename your project path or add follow code in chainWebpack function to solve it.

May be your project path has a special symbol like ‘(‘ or ‘)’

tested with and without parenthesis in path. You are correct. This is seems to be the problem.

May be your project path has a special symbol like ‘(‘ or ‘)’
You are absolutely correct! I solved this problem by removing parentesis from the path. Thank you 🙂

@Luiz-Soft which path bro please help i am also facing this kind of problem

@Luiz-Soft which path bro please help i am also facing this kind of problem

The absolute path of your project

May be your project path has a special symbol like ‘(‘ or ‘)’. I’m not sure if it’s a bug of copy-webpack-plugin or fast-glob, because cli will add the absolute path of the index.html in the public folder to the ignore list, if the path has a special symbol, copy-webpack-plugin will not match the path and will not ignore it. Therefore index.html will emit twice. You can rename your project path or add follow code in chainWebpack function to solve it.

This helps me a lot. Thanks Sir

This problem occurs in vue-cli v5.0.8 as well. Removing the parenthesis also removes the issue with this version.

Got the same issue. Unfortunately, I don’t have any parenthesis in my path. Any recommendations on what to do? I cannot really downgrade as lower versions bring with them a lot of vulnerabilities in dependencies.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Vue version 5.0.1. After downloading, run NPM run serve to report an error #7043

Version

Environment info

Steps to reproduce

Follow the normal installation steps, and then report an error when running NPM run serve:
Conflict: Multiple assets emit different content to the same filename index. html
ERROR in Conflict: Multiple assets emit different content to the same filename index. html
webpack compiled with 1 error

What is expected?

How to solve it?

What is actually happening?

Conflict: Multiple assets emit different content to the same filename index.html
ERROR in Conflict: Multiple assets emit different content to the same filename index.html
webpack compiled with 1 error

The text was updated successfully, but these errors were encountered:

Have you solved the problem?
问题解决了吗?

Same problem with @vue/cli 5.0.1, Node v14.17.5, vue 3.2.13, and npm 7.20.6

Edit: Downgraded to @vue/cli 4.5.15, works now

Same problem with @vue/cli 5.0.1, Node v14.17.5, vue 3.2.13, and npm 7.20.6

Edit: Downgraded to @vue/cli 4.5.15, works now

it works. thank you.

May be your project path has a special symbol like ‘(‘ or ‘)’. I’m not sure if it’s a bug of copy-webpack-plugin or fast-glob, because cli will add the absolute path of the index.html in the public folder to the ignore list, if the path has a special symbol, copy-webpack-plugin will not match the path and will not ignore it. Therefore index.html will emit twice. You can rename your project path or add follow code in chainWebpack function to solve it.

May be your project path has a special symbol like ‘(‘ or ‘)’

tested with and without parenthesis in path. You are correct. This is seems to be the problem.

May be your project path has a special symbol like ‘(‘ or ‘)’
You are absolutely correct! I solved this problem by removing parentesis from the path. Thank you 🙂

@Luiz-Soft which path bro please help i am also facing this kind of problem

@Luiz-Soft which path bro please help i am also facing this kind of problem

The absolute path of your project

May be your project path has a special symbol like ‘(‘ or ‘)’. I’m not sure if it’s a bug of copy-webpack-plugin or fast-glob, because cli will add the absolute path of the index.html in the public folder to the ignore list, if the path has a special symbol, copy-webpack-plugin will not match the path and will not ignore it. Therefore index.html will emit twice. You can rename your project path or add follow code in chainWebpack function to solve it.

This helps me a lot. Thanks Sir

This problem occurs in vue-cli v5.0.8 as well. Removing the parenthesis also removes the issue with this version.

Got the same issue. Unfortunately, I don’t have any parenthesis in my path. Any recommendations on what to do? I cannot really downgrade as lower versions bring with them a lot of vulnerabilities in dependencies.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

WARNING in Conflict: Multiple assets emit different content to the same filename 3rdpartylicenses.txt #16193

Command (mark with an x )

Is this a regression?

Description

The following warning appears on production builds:

🔬 Minimal Reproduction

  • clone https://github.com/johannesjo/super-productivity
  • update to latest CLI, FW, and Material
  • add the following ngcc.onfig.js

🔥 Exception or Error

🌍 Your Environment

The text was updated successfully, but these errors were encountered:

The LicenseWebpackPlugin (https://github.com/xz64/license-webpack-plugin) emits the 3rdpartylicenses.txt file. The plugin uses the webpack compilation hook optimizeChunkAssetwhich can be called multiple times within a single compilation. (code: https://github.com/xz64/license-webpack-plugin/blob/master/src/WebpackCompilerHandler.ts#L27) This is the source of the multiple license assets. One case of this hook being called multiple times is the presence of stylesheets within the projects styles option. The MiniCssExtractPlugin used to output the CSS appears to call the hook while extracting the stylesheets from the internal webpack javascript variant of the stylesheet.

The emit hook would most likely be the more appropriate hook to use as this is called once at the completion of the compilation to output the files. This would necessitate a change to the plugin itself which is third-party.

An alternative could be to switch plugins to https://github.com/microsoft/license-checker-webpack-plugin which uses the emit hook.

The most obvious fix would be to update license-webpack-plugin to use the emit hook, however this could have ripple effects for the rest of the repo. Even if we fix the problem there, it may take some time for a stable release which we can depend on, which likely won’t make the v9 release timeframe.

The other option would be to switch to Microsoft’s license-checker-webpack-plugin , though this is probably more overall effort and would probably make google3 integration harder (Edit: @angular-devkit/build-angular is not included in the g3 build pipeline).

Источник

Error: Conflict: Multiple chunks emit assets to the same filename ssr-bundle.js #29

Hi, I have encountered this problem when I was trying to create multiple html files with multiple entries.

I have tried below but doesnt make any difference.

The text was updated successfully, but these errors were encountered:

template: `!!prerender-loader?string!$/template.html` locates in production.config.js file

I think I found the issue, I was using os.tmpdir() , but had meant to use fs.mkdtempSync() .

@edwardfhsiao alright, I figured out the issue with the demo you linked above: it’s a duplicate of #25, and the solution I posted there a couple hours ago works here too:

@developit Awesome, that solved my problem. Really appreciate your help!

This issue may have to be looked at again. The error still occurs if using the <> in the template tag as specified in the docs:
https://github.com/GoogleChromeLabs/prerender-loader#injecting-content-into-the-html

I spent many hours trying to debug our config and was still getting the multiple chunks error until i realized this.

To replicate, replace the template.html file in the example repo (https://github.com/edwardfhsiao/prerender-loader-test-repo) with:

and run npm run compile or yarn compile .

It’s not clear where the formatting comes from, but using <> in the template as specified in the docs fails with multiple entry files.

Источник

Конфликт: несколько ресурсов отправляются в одно и то же имя файла

Я новичок в Webpack, который хочет узнать об этом все. Я столкнулся с конфликтом при запуске своего веб-пакета, который сказал мне:

ERROR in chunk html [entry] app.js Conflict: Multiple assets emit to the same filename app.js

Что мне делать, чтобы избежать конфликта?

Это мой webpack.config.js:

Я не совсем знаком с вашим подходом, поэтому я покажу вам общий способ помочь вам.

Прежде всего, на ваш output , вы указав filename на app.js что имеет смысл для меня , что выход все равно будет app.js . Если вы хотите сделать его динамичным, просто используйте «filename»: «[name].js» .

Эта [name] часть сделает имя файла динамическим для вас. Это цель вашего entry объекта. Каждый ключ будет использоваться как имя вместо расширения [name].js .

Во-вторых, вы можете использовать расширение html-webpack-plugin . Вам не нужно включать его как test .

У меня была такая же проблема, я обнаружил, что это установка статического имени выходного файла, которое вызывает мою проблему, в выходном объекте попробуйте следующий объект.

Это делает так, что имена файлов разные и не конфликтуют.

РЕДАКТИРОВАТЬ: Одна вещь, которую я недавно обнаружил, заключается в том, что вы должны использовать хеш вместо chunkhash при использовании перезагрузки HMR. Я не вникал в корень проблемы, но просто знаю, что использование chunkhash нарушает мою конфигурацию веб-пакета

Тогда должно работать нормально с HMR 🙂

ИЗМЕНИТЬ июль 2018 г .:

Еще немного информации об этом.

Хеш. Это хэш, который генерируется каждый раз при компиляции webpack. В режиме разработки он хорош для очистки кеша во время разработки, но не должен использоваться для длительного кеширования ваших файлов. Это перезапишет хэш при каждой сборке вашего проекта.

Chunkhash Если вы используете это в сочетании с фрагментом времени выполнения, вы можете использовать его для долгосрочного кэширования, фрагмент времени выполнения увидит, что изменилось в вашем исходном коде, и обновит хэши соответствующих фрагментов. Он не будет обновлять другие, позволяя кэшировать ваши файлы.

Источник

I’m a webpack rookie who wants to learn all about it.
I came across a conflict when running my webpack telling me:

ERROR in chunk html [entry] app.js Conflict: Multiple assets emit to
the same filename app.js

What should I do to avoid the conflict?

This is my webpack.config.js:

module.exports = {
  context: __dirname + "/app",

  entry: {
    'javascript': "./js/app.js",
    'html': "./index.html",
  },
  output: {
    path: __dirname + "/dist",
    filename: "app.js",
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        loaders: ["babel-loader"]
      },
      {
        test: /.html$/,
        loader: "file-loader?name=[name].[ext]",
      }
    ]
  }
};
1) Solution

i’m not quite familiar with your approach so I’ll show you a common way to help you out.

First of all, on your output, you are specifying the filename to app.js which makes sense for me that the output will still be app.js. If you want to make it dynamic, then just use "filename": "[name].js".

The [name] part will make the filename dynamic for you. That’s the purpose of your entry as an object. Each key will be used as a name in replacement of the [name].js.

And second, you can use the html-webpack-plugin. You don’t need to include it as a test.

2) Solution

I had the same problem, I found it was setting a static output file name that was causing my problem, in the output object try the following object.

output:{
        filename: '[name].js',
        path: __dirname + '/build',
        chunkFilename: '[id].[chunkhash].js'
    },

This makes it so that the filenames are different and it doesn’t clash.

EDIT:
One thing i’ve recently found is that you should use a hash instead of chunkhash if using HMR reloading. I haven’t dug into the root of the problem but I just know that using chunkhash was breaking my webpack config

output: {
  path: path.resolve(__dirname, 'dist'),
  filename: '[name].[hash:8].js',
  sourceMapFilename: '[name].[hash:8].map',
  chunkFilename: '[id].[hash:8].js'
};

Should work fine with HMR then :)

EDIT July 2018:

A little more information on this.

Hash
This is a hash generated every time that webpack compiles, in dev mode this is good for cache busting during development but shouldn’t be used for long term caching of your files. This will overwrite the Hash on every build of your project.

Chunkhash
If you use this in conjunction with a runtime chunk then you can use it for long term caching, the runtime chunk will see what’s changed in your source code and update the corresponding chunks hash’s. It won’t update others allowing for your files to be cached.

3) Solution

I had exactly the same problem. The problem seems to occur with the file-loader. The error went away when I removed the html test and included html-webpack-plugin instead to generate an index.html file. This is my webpack.config.js file:

var path = require('path');

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/app/index.html',
  filename: 'index.html',
  inject: 'body'
})

module.exports = { 
  entry: {
    javascript: './app/index.js',
  },  

  output: {
    filename: 'bundle.js',
    path: __dirname + '/dist'
  },  

  module: {
    rules: [
      {   
        test: /.jsx?$/,
        exclude: [
          path.resolve(__dirname, '/node_modules/')
        ],  
        loader: 'babel-loader'
      },  
    ]   
  },  

  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },  

  plugins: [HTMLWebpackPluginConfig]
}

The html-webpack-plugin generates an index.html file and automatically injects the bundled js file into it.

4) Solution

I had the same issue after upgrading to Webpack 5. My problem was caused by the copy-webpack-plugin.

Below is the original pattern ignoring a specified file, it works with Webpack 4, but throws an error with Webpack 5.

ERROR in Conflict: Multiple assets emit different content to the same
filename default.hbs

  plugins: [
   new CopyPlugin({
      patterns: [
        {
          from: "./src/academy/templates",
          globOptions: {
            ignore: ["default.hbs"]
          }
        },
      ]
    }),
   ],

To fix the error:

  plugins: [
   new CopyPlugin({
      patterns: [
        {
          from: "./src/academy/templates",
          globOptions: {
            ignore: ["**/default.hbs"]
          }
        },
      ]
    }),
   ],

By not ignoring the specified file, the default.hbs (a.k.a index.html) was copied twice into the build (a.k.a /disk) directory effectively resulting in Webpack trying to insert multiple assets into the «same» (duplicated) filename.

5) Solution

I had the same problem, and I found these in the documents.

If your configuration creates more than a single “chunk” (as with multiple entry points or when using plugins like CommonsChunkPlugin), you should use substitutions to ensure that each file has a unique name.

  • [name] is replaced by the name of the chunk.
  • [hash] is replaced by the hash of the compilation.
  • [chunkhash] is replaced by the hash of the chunk.
 output: {
    path:__dirname+'/dist/js',

    //replace filename:'app.js' 
    filename:'[name].js'
}
6) Solution

I encountered this error in my local dev environment. For me, the solution to this error was to force the files to rebuild. To do this, I made a minor change to one of my CSS files.

I reloaded my browser and the error went away.

7) Solution

In my case the source map plugin was conflicting with the extract mini plugin.
Could not find a solution to this anywhere. source maps for css and javascript were writing to the same file. Here is how I finally solved it in my project:

new webpack.SourceMapDevToolPlugin({
    filename: '[name].[ext].map'
}),
8) Solution

I had the same problem after updating all the dependencies to latest (e.g. webpack 4 -> 5) for a Chrome extension I made about 2 years ago, and managed to solve it.

There were two files in the complaint (popup.html and options.html). Here is my original webpack.config.js file:

const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
    target: 'web',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
    },
    entry: {
        popup: './src/scripts/popup.tsx',
        options: './src/scripts/options.tsx',
    },
    context: path.join(__dirname),
    module: {
        rules: [
            {
                test: /.tsx?$/,
                loader: 'ts-loader',
            },
            {
                test: /.css$/,
                use: [
                    'style-loader',
                    'css-loader',
                ],
            },
            {
                test: /.scss$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader',
                ],
            },
        ],
    },

    resolve: {
        extensions: ['.tsx', '.ts', '.js', '.json', '.css'],
    },
    plugins: [
        new CleanWebpackPlugin(),
        new CopyPlugin([
            { from: 'src/popup.html', to: 'popup.html' },
            { from: 'src/options.html', to: 'options.html' },
            { from: 'src/manifest.json', to: 'manifest.json' },
            { from: 'src/icons', to: 'icons' },
        ]),
        new HtmlWebpackPlugin({
            template: path.join("src", "popup.html"),
            filename: "popup.html",
            chunks: ["popup"]
        }),
        new HtmlWebpackPlugin({
            template: path.join("src", "options.html"),
            filename: "options.html",
            chunks: ["options"]
        }),
    ]
};

I solved it by removing:

            { from: 'src/popup.html', to: 'popup.html' },
            { from: 'src/options.html', to: 'options.html' },

under new CopyPlugin... part.

So seems like right now there is no need to explicitly copy popup.html and options.html to output folder when HtmlWebpackPlugin is already emitting them.

9) Solution

Similar solution to the above with file-loader, however, I think this solution is the more elegant. Before, I was only specifying the [name], adding the [path][name] resolved my conflict as below:

module: {
rules: [
  {
    test: /.(mp4|m4s)$/,
    use: [
      {
        loader: 'file-loader',
        options: {
          name: '[path][name].[ext]',
        },
      },
    ],
  },
],
10) Solution

I changed index.html file from /public directory to /src to fix this issue. (Webpack 5.1.3)

11) Solution

The same error in a Vue.js project when doing e2e with Karma. The page was served using a static template index.html with /dist/build.js. And got this error running Karma.

The command to issue Karma using package.json was:

"test": "cross-env BABEL_ENV=test CHROME_BIN=$(which chromium-browser) karma start --single-run"

The output configuration in webpack.config.js was:

 module.exports = {
  output: {
   path: path.resolve(__dirname, './dist'),
   publicPath: '/dist/',
   filename: 'build.js'
  },
  ...
 }

My solution: inspired by the Evan Burbidge’s answer I appended the following at the end of webpack.config.js:

if (process.env.BABEL_ENV === 'test') {
  module.exports.output.filename = '[name].[hash:8].js'
}

And then it eventually worked for both page serving and e2e.

Comments Section

This solved my issue as well. It seems you can have the HTMLWebpackPlugin, or the html-loader, but not both.

it would be great if this had a sample that matched the original

Wanted to use asyncComponent. Then I found this problem with a file which was before in other component. Simple restarting yarn fixed that. Thanks!

what I want to know is what tool writes an error like «Conflict: Multiple assets emit to the same filename slots.js». Why would you not put the damn names of the conflicting assets in that error instead of forcing the user to track it down???

Good news! The error has been updated. It now helpfully reads Conflict: Multiple chunks emit assets to the same filename main.css (chunks main and main)

Hi, what the :8 stand for? thx

@funder7 the first 8 characters from the file’s hash

Related Topics
javascript
node.js
config
conflict
webpack

Mentions
Soviut
Masih Jahangiri
Dieter Gribnitz
Saurabh Mistry
Juri Sinitson
Evan Burbidge
Ickyrr
Mr Good
Andreasrein
Iyashi
Lukastillmann
Ksan
Hxin
Akira Suto Xiaowei Zhou
Belfield
Jiso Chacko

References
42148632/conflict-multiple-assets-emit-to-the-same-filename

I’m a webpack rookie who wants to learn all about it.
I came across a conflict when running my webpack telling me:

ERROR in chunk html [entry] app.js Conflict: Multiple assets emit to
the same filename app.js

What should I do to avoid the conflict?

This is my webpack.config.js:

module.exports = {
  context: __dirname + "/app",

  entry: {
    'javascript': "./js/app.js",
    'html': "./index.html",
  },
  output: {
    path: __dirname + "/dist",
    filename: "app.js",
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        loaders: ["babel-loader"]
      },
      {
        test: /.html$/,
        loader: "file-loader?name=[name].[ext]",
      }
    ]
  }
};

9 Answers

i’m not quite familiar with your approach so I’ll show you a common way to help you out.

First of all, on your output, you are specifying the filename to app.js which makes sense for me that the output will still be app.js. If you want to make it dynamic, then just use "filename": "[name].js".

The [name] part will make the filename dynamic for you. That’s the purpose of your entry as an object. Each key will be used as a name in replacement of the [name].js.

And second, you can use the html-webpack-plugin. You don’t need to include it as a test.

I had the same problem, I found it was setting a static output file name that was causing my problem, in the output object try the following object.

output:{
        filename: '[name].js',
        path: __dirname + '/build',
        chunkFilename: '[id].[chunkhash].js'
    },

This makes it so that the filenames are different and it doesn’t clash.

EDIT:
One thing i’ve recently found is that you should use a hash instead of chunkhash if using HMR reloading. I haven’t dug into the root of the problem but I just know that using chunkhash was breaking my webpack config

output: {
  path: path.resolve(__dirname, 'dist'),
  filename: '[name].[hash:8].js',
  sourceMapFilename: '[name].[hash:8].map',
  chunkFilename: '[id].[hash:8].js'
};

Should work fine with HMR then :)

EDIT July 2018:

A little more information on this.

Hash
This is a hash generated every time that webpack compiles, in dev mode this is good for cache busting during development but shouldn’t be used for long term caching of your files. This will overwrite the Hash on every build of your project.

Chunkhash
If you use this in conjunction with a runtime chunk then you can use it for long term caching, the runtime chunk will see what’s changed in your source code and update the corresponding chunks hash’s. It won’t update others allowing for your files to be cached.

I had exactly the same problem. The problem seems to occur with the file-loader. The error went away when I removed the html test and included html-webpack-plugin instead to generate an index.html file. This is my webpack.config.js file:

var path = require('path');

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/app/index.html',
  filename: 'index.html',
  inject: 'body'
})

module.exports = { 
  entry: {
    javascript: './app/index.js',
  },  

  output: {
    filename: 'bundle.js',
    path: __dirname + '/dist'
  },  

  module: {
    rules: [
      {   
        test: /.jsx?$/,
        exclude: [
          path.resolve(__dirname, '/node_modules/')
        ],  
        loader: 'babel-loader'
      },  
    ]   
  },  

  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },  

  plugins: [HTMLWebpackPluginConfig]
}

The html-webpack-plugin generates an index.html file and automatically injects the bundled js file into it.

I had the same problem, and I found these in the documents.

If your configuration creates more than a single “chunk” (as with multiple entry points or when using plugins like CommonsChunkPlugin), you should use substitutions to ensure that each file has a unique name.

  • [name] is replaced by the name of the chunk.
  • [hash] is replaced by the hash of the compilation.
  • [chunkhash] is replaced by the hash of the chunk.
 output: {
    path:__dirname+'/dist/js',

    //replace filename:'app.js' 
    filename:'[name].js'
}

I encountered this error in my local dev environment. For me, the solution to this error was to force the files to rebuild. To do this, I made a minor change to one of my CSS files.

I reloaded my browser and the error went away.

I had the same issue after upgrading to Webpack 5. My problem was caused by the copy-webpack-plugin.

Below is the original pattern ignoring a specified file, it works with Webpack 4, but throws an error with Webpack 5.

ERROR in Conflict: Multiple assets emit different content to the same
filename default.hbs

  plugins: [
   new CopyPlugin({
      patterns: [
        {
          from: "./src/academy/templates",
          globOptions: {
            ignore: ["default.hbs"]
          }
        },
      ]
    }),
   ],

To fix the error:

  plugins: [
   new CopyPlugin({
      patterns: [
        {
          from: "./src/academy/templates",
          globOptions: {
            ignore: ["**/default.hbs"]
          }
        },
      ]
    }),
   ],

By not ignoring the specified file, the default.hbs (a.k.a index.html) was copied twice into the build (a.k.a /disk) directory effectively resulting in Webpack trying to insert multiple assets into the «same» (duplicated) filename.

The same error in a Vue.js project when doing e2e with Karma. The page was served using a static template index.html with /dist/build.js. And got this error running Karma.

The command to issue Karma using package.json was:

"test": "cross-env BABEL_ENV=test CHROME_BIN=$(which chromium-browser) karma start --single-run"

The output configuration in webpack.config.js was:

 module.exports = {
  output: {
   path: path.resolve(__dirname, './dist'),
   publicPath: '/dist/',
   filename: 'build.js'
  },
  ...
 }

My solution: inspired by the Evan Burbidge’s answer I appended the following at the end of webpack.config.js:

if (process.env.BABEL_ENV === 'test') {
  module.exports.output.filename = '[name].[hash:8].js'
}

And then it eventually worked for both page serving and e2e.

I changed index.html file from /public directory to /src to fix this issue. (Webpack 5.1.3)

I had the same problem after updating all the dependencies to latest (e.g. webpack 4 -> 5) for a Chrome extension I made about 2 years ago, and managed to solve it.

There were two files in the complaint (popup.html and options.html). Here is my original webpack.config.js file:

const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
    target: 'web',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
    },
    entry: {
        popup: './src/scripts/popup.tsx',
        options: './src/scripts/options.tsx',
    },
    context: path.join(__dirname),
    module: {
        rules: [
            {
                test: /.tsx?$/,
                loader: 'ts-loader',
            },
            {
                test: /.css$/,
                use: [
                    'style-loader',
                    'css-loader',
                ],
            },
            {
                test: /.scss$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader',
                ],
            },
        ],
    },

    resolve: {
        extensions: ['.tsx', '.ts', '.js', '.json', '.css'],
    },
    plugins: [
        new CleanWebpackPlugin(),
        new CopyPlugin([
            { from: 'src/popup.html', to: 'popup.html' },
            { from: 'src/options.html', to: 'options.html' },
            { from: 'src/manifest.json', to: 'manifest.json' },
            { from: 'src/icons', to: 'icons' },
        ]),
        new HtmlWebpackPlugin({
            template: path.join("src", "popup.html"),
            filename: "popup.html",
            chunks: ["popup"]
        }),
        new HtmlWebpackPlugin({
            template: path.join("src", "options.html"),
            filename: "options.html",
            chunks: ["options"]
        }),
    ]
};

I solved it by removing:

            { from: 'src/popup.html', to: 'popup.html' },
            { from: 'src/options.html', to: 'options.html' },

under new CopyPlugin... part.

So seems like right now there is no need to explicitly copy popup.html and options.html to output folder when HtmlWebpackPlugin is already emitting them.

Понравилась статья? Поделить с друзьями:
  • Error in communication with engine kerio control
  • Error in command syntax check command help
  • Error in command line need pyserial path as 1st arg and esptool path as 2nd
  • Error in command line daemon tools
  • Error in color linetype argument