Can't load png and gif images in webpack.config.js
This issue came while running unit test using Mocha-webpack.
Here I have pasted my webpack.config.js.
How can I fix this issue??
I have tried with the image loader too for fix this, It won't work.
Any other way to fix this type of loader issue?
Here is the screenshot for that issue
'use strict'
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
// output: {
// path: path.resolve(__dirname, './dist'),
// publicPath: '/dist/',
// filename: 'build.js'
// },
resolve: {
extensions: ['.js', '.jsx', '.css'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': path.resolve(__dirname, 'src')
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg|css|eot|ttf)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
},
{
test: /\.(jpg|jpeg|gif|png|css)$/,
loader: [ 'css-loader' ]
},
{
test: /\.(jpg|jpeg|gif|png)$/,
loader:'url-loader?limit=1024&name=images/[name].[ext]'
},
{
test: /\.(woff|woff2|eot|ttf|svg|png|gif)$/,
loader: 'url-loader?limit=1024&name=fonts/[name].[ext]'
},
{
test: /\.(png|jpg|svg)$/,
loader: 'file-loader',
query: {
name: './src/assets/[name]-[sha512:hash:base64:7].[ext]',
},
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|eot|ttf)$/,
loader:['url-loader?limit=10000',
'img-loader']
},
{
test: /\.(woff(2)?|ttf|eot|png|gif|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}]
}
]
},
devServer: {
historyApiFallback: true,
noInfo: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
// test specific setups
if (process.env.NODE_ENV === 'test') {
module.exports.externals = [require('webpack-node-externals')()]
module.exports.devtool = 'eval'
devtool: 'inline-cheap-module-source-map'
}
Did you try using url-loader for loading images?
Like just replacing
{
test: /\.(png|jpg|gif|svg|css|eot|ttf)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
with
{
test: /\.(png|jpg|gif|svg|css|eot|ttf)$/,
loader: 'url-loader',
}
Related
I've been working on using ModuleFederation and have ran into an issue where if the remote webpack configuration had optimize.splitChunks.chunk = "all" then the host application would throw a loadScript exception. This could be a complete fundamental knowledge gap on my part why that wouldn't work. I haven't seen any documentation on not using that option along with Module Federation.
Has anyone had similar experiences or can tell me why it's a conflicting setting?
Thanks for your help!
remote webpack.config.js
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { ModuleFederationPlugin } = webpack.container;
module.exports = {
entry: "./index.js",
mode: "development",
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 1338,
},
output: {
publicPath: "auto",
},
optimization: {
splitChunks: {
chunk: "all"
}
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: "babel-loader",
exclude: /node_modules/,
options: {
presets: ["#babel/preset-react"],
},
},
],
},
plugins: [
new ModuleFederationPlugin({
name: "comic",
filename: "remoteEntry.js",
exposes: {
"./XKCD": "./app.jsx",
},
shared: [
{
react: { singleton: true, eager: true },
"react-dom": { singleton: true, eager: true },
},
],
}),
new HtmlWebpackPlugin({
template: "./index.html",
}),
],
};
host webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ModuleFederationPlugin = require("webpack").container
.ModuleFederationPlugin;
const path = require("path");
module.exports = {
entry: "./index.js",
mode: "development",
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 1337,
},
output: {
publicPath: "auto",
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: "babel-loader",
exclude: /node_modules/,
options: {
presets: ["#babel/preset-react"],
},
},
],
},
plugins: [
new ModuleFederationPlugin({
name: "home",
filename: "remoteEntry.js",
remotes: {
comic: `comic#http://localhost:1338/remoteEntry.js)`,
},
shared: [
{
react: { singleton: true, eager: true },
"react-dom": { singleton: true, eager: true },
},
],
}),
new HtmlWebpackPlugin({
template: "./index.html",
}),
],
};
I have a similar problem.
I change the remote webpack.config.js optimization.splitChunks as
optimization: {
splitChunks: {
chunks: 'async'
}
}
This problem is fixed.
Maybe you can try it.
Sorry my pool english
I am getting this error when I run the app:
ERROR in ./node_modules/primereact/resources/themes/saga-blue/theme.css (./node_modules/css-loader!./node_modules/style-loader!./node_modules/css-loader!./node_modules/primereact/resources/themes/saga-blue/theme.css)
Module build failed (from ./node_modules/css-loader/index.js):
Unknown word (2:1)
1 |
> 2 | var content = require("!!../../../../css-loader/index.js!./theme.css");
| ^
3 |
4 | if(typeof content === 'string') content = [[module.id, content, '']];
5 |
# ./node_modules/primereact/resources/themes/saga-blue/theme.css 2:14-136 21:1-42:3 22:19-141
# ./src/index.js
I have not modified any of the common, dev and prod webpacks. I've read the other 2 questions posted around this but none of the answers worked.
I'll post the webpack configurations for your convenience.
Common:
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: path.resolve(__dirname, "../src", "index.js"),
},
output: {
filename: '[name].[hash].js',
path: path.resolve(__dirname, '../dist'),
publicPath: "/"
},
devServer: {
port: 3042,
historyApiFallback: true,
overlay: true,
open: true,
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: [/node_modules/],
use: [{ loader: "babel-loader" }]
},
{
test: /.*\.(gif|png|jp(e*)g|svg)$/i,
use: [
{
loader: "url-loader",
options: {
limit: 21000,
name: "images/[name]_[hash:7].[ext]"
}
}
]
},
// Vendor CSS loader
// This is necessary to pack third party libraries like antd
{
test: /\.css$/,
include: path.resolve(__dirname, '../node_modules'),
use: [
'style-loader',
'css-loader'
],
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: path.resolve(__dirname, '../public', 'index.html'),
}),
],
resolve: {
extensions: ['.js', '.jsx']
},
}
Dev:
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const mapStyle = process.env.MAP_STYLE === 'true';
module.exports = merge (common, {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
port: 3042,
historyApiFallback: true,
overlay: true,
open: true,
stats: 'errors-only'
},
module: {
rules: [
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: mapStyle ? "css-loader?sourceMap" : "css-loader" }
]
},
{
test: /\.s(a|c)ss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
}),
],
});
Prod:
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ManifestPlugin = require('webpack-manifest-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const enableBundleAnalyzer = process.env.ENABLE_ANALYZER === 'true';
module.exports = merge(common, {
mode: 'production',
devtool: 'source-map',
module: {
rules: [
{
test: /\.css$/,
use: [
{ loader: MiniCssExtractPlugin.loader },
{ loader: "css-loader" }
]
},
{
test: /\.s(a|c)ss$/,
use: [
{ loader: MiniCssExtractPlugin.loader },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
},
]
},
optimization: {
splitChunks: {
chunks: 'all',
},
runtimeChunk: false,
},
plugins: [
new CleanWebpackPlugin([path.resolve(__dirname, '../dist')], {
root: process.cwd(),
verbose: true,
dry: false
}),
new OptimizeCssAssetsPlugin(),
new MiniCssExtractPlugin({
filename: "[name].[hash:8].css",
chunkFilename: "[id].[hash:8].css"
}),
new ManifestPlugin(),
new BundleAnalyzerPlugin({
analyzerMode: enableBundleAnalyzer === true ? 'static' : 'disabled',
openAnalyzer: true,
}),
],
});
And here is where I import them:
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import App from './components/App';
import store from './app/store';
import './assets/styles/style.sass';
import './assets/styles/style.css';
import './index.scss';
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';
import 'primeflex/primeflex.css';
import 'primereact/resources/themes/saga-blue/theme.css';
import '/src/assets/styles/customTheme.scss';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
// Check if hot reloading is enable. If it is, changes won't reload the page.
// This is related to webpack-dev-server and works on development only.
if (module.hot) {
module.hot.accept();
}
One of the questions answered this by saying that i needed the url-loader but, as you can see, the boilerplate contains that aswell.
I hope I gave you enough information. Thank you in advance.
I think I've found my answer. I needed to exclude node_modules from the css loader rules from both the dev and prod configurations since the common configuration was handling that. The error was thrown because there were 2 conflicting css loaders.
I want to have some dependencies in different chunks so client.js would be smaller. webpack 4.16.5
Why I get same code included to several chunks? What's missing?
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
mode: 'production',
target: 'web',
// devtool: 'source-map',
entry: {
echarts: ['echarts'],
vendor_1: ['react', 'immutable', 'lodash', 'redux', 'redux-saga'],
vendor_2: ['#material-ui/core', '#tinymce/tinymce-react'],
client: ['babel-polyfill', path.join(__dirname, 'app/index.js')],
},
output: {
path: path.join(__dirname, '/dist/'),
filename: '[hash].[name].js',
publicPath: './',
},
resolve: {
modules: [
path.join(__dirname, '/app'),
'node_modules',
],
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
template: 'app/index.tpl.html',
inject: 'body',
filename: 'index.html',
}),
new BundleAnalyzerPlugin(),
],
module: {
rules: [
{
test: /\.js?$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
}],
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader?modules&localIdentName=[name]---[local]---[hash:base64:5]',
'sass-loader',
],
},
{
test: /\.woff(2)?(\?[a-z0-9#=&.]+)?$/,
use: [{
loader: 'url?limit=10000&mimetype=application/font-woff',
}],
},
{
test: /\.(ttf|eot|svg)(\?[a-z0-9#=&.]+)?$/,
use: [{
loader: 'file',
}],
},
],
},
};
I added optimization config and it works now as expected.
optimization: {
splitChunks: {
chunks: 'initial',
},
},
I've played with values a bit and this was the best result for my code base without any extra code edits. You can find all possible options here:
https://webpack.js.org/configuration/optimization/
Thanks Pavel for the tip ;)
I am able to set up Unit test framework using Karma, Webpack and karma-remap-coverage for code coverage. But I don't understand why coverage is not coming for all the files(components, directives, services). I have around, supposed 100 files, but it's generating coverage report only for 40-50 files.
Here I am sharing my configuration files:
Karma.conf.js
var webpackConfig = require('./webpack/webpack.test');
var path = require('path');
module.exports = function (config) {
var _config = {
basePath: '',
frameworks: ['jasmine'],
files: [
{ pattern: './webpack/karma-test-shim.js', watched: false },
{ pattern: './node_modules/#angular/material/prebuilt-themes/indigo-pink.css', included: true, watched: false }
],
preprocessors: {
'./webpack/karma-test-shim.js': ['webpack', 'sourcemap'],
},
webpack: webpackConfig,
webpackMiddleware: {
stats: 'errors-only'
},
webpackServer: {
noInfo: true
},
coverageReporter: {
includeAllSources: true,
type: 'html',
dir: 'coverage/'
},
// coverageIstanbulReporter: {
// reports: ['html', 'lcovonly'],
// fixWebpackSourcePaths: true
// },
// reporters: ['progress', 'coverage-istanbul'],
coverageReporter: {
type: 'in-memory'
},
remapCoverageReporter: {
'text-summary': null,
json: './coverage/coverage.json',
html: './coverage/html',
cobertura: './coverage/cobertura.xml'
},
reporters: ['progress', 'coverage', 'remap-coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
singleRun: true,
browserNoActivityTimeout: 20000
};
config.set(_config);
};
Webpack.test.js
var webpack = require('webpack');
var helpers = require('./helpers');
var path = require('path');
module.exports = {
devtool: 'inline-source-map',
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loaders: [
{
loader: 'awesome-typescript-loader?sourceMap=false,inlineSourceMap=true',
options: { configFileName: 'tsconfig.json' }
}, 'angular2-template-loader'
]
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'null-loader'
},
{
test: /\.css$/,
exclude: helpers.root('app'),
loader: 'null-loader'
},
{
test: /\.css$/,
include: helpers.root('app'),
loader: 'raw-loader'
},
{
enforce: 'post',
test: /\.ts$/,
loader: 'istanbul-instrumenter-loader',
include: helpers.root('app'),
exclude: /(node_modules|\.spec\.ts)/
}
]
}
}
Karma-test-shim.js
Error.stackTraceLimit = Infinity;
require('core-js/es6');
require('core-js/es7/reflect');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
var appContext = require.context('../testing/specs', true, /\.spec\.ts/);
appContext.keys().forEach(appContext);
var testing = require('#angular/core/testing');
var browser = require('#angular/platform-browser-dynamic/testing');
testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());
NPM dependencies used:
"karma": "^1.2.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "~1.0.1",
"karma-coverage": "^1.1.1",
"istanbul-instrumenter-loader": "2.0.0",
"karma-html-reporter": "^0.2.7",
"karma-jasmine": "^1.0.2",
"karma-jasmine-html-reporter": "^0.2.2",
"karma-mocha-reporter": "^2.2.3",
"karma-remap-coverage": "^0.1.2",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^2.0.1",
Any help is really appreciated!
I'm not sure why my front end isn't running in hot mode. I am trying to decouple the front end and backend as much as possible. The only thing that connects the two is that I use django's webpack_loader app to load the webpack build to load into a template (index.html).
My backend is in Django and it is currently running on http://127.0.0.1:8000/.
My frontend is hosted on localhost:8080
My devServer for hot mode is on 0.0.0.0:8080
I tried changing a bit of my front end and saving it to see what would happen and nothing on the front end has been updated. In my developer tools I see this:
[HMR] Update check failed: SyntaxError: Unexpected token <
at Object.parse (native)
at XMLHttpRequest.request.onreadystatechange (http://localhost:8000/static/js/main.js:44:33)
Here are my npm scripts:
"scripts": {
"watch-client": "node ./node_modules/webpack/bin/webpack.js --verbose --colors --display-error-details --config webpack.watch.js && node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --config webpack.watch.js",
"watch": "npm run watch-client"
},
webpack.config.js:
var path = require('path')
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: [
'./app/index.js'
],
output: {
path: path.resolve(__dirname, 'public'),
publicPath: '/js/',
filename: 'main.js'
},
devtool: 'eval',
debug: true,
module: {
loaders: [
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.jsx$/, loader: 'jsx-loader' },
{ test: /\.es6$/, exclude: /node_modules/, loader: 'babel-loader?stage=0&optional=runtime'},
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?stage=0&optional=runtime'},
{ test: /\.less$/, exclude: /node_modules/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")},
{ test: /\.css$/, exclude: /node_modules/, loader: 'style-loader!css-loader' }
]
},
plugins: [
new ExtractTextPlugin('style.css', {
allChunks: true
}),
new webpack.optimize.CommonsChunkPlugin('common.js'),
]
};
webpack.watch.js:
var Webpack = require("webpack");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var config = require("./webpack.config.js");
var BundleTracker = require('webpack-bundle-tracker');
var port = process.env.WEBPACK_PORT || 8080;
var host = process.env.HOST || 'localhost';
// add hot loader
config.entry.unshift(
"webpack-dev-server/client?http://" + host + ":" + port,
"webpack/hot/only-dev-server" // only prevents reload on syntax errors
);
config.plugins = [
new ExtractTextPlugin("style.css", {
allChunks: true
}),
new Webpack.HotModuleReplacementPlugin(),
new BundleTracker({filename: './webpack-stats.json'})
];
config.module.loaders = [
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.jsx$/, loader: 'jsx-loader' },
{ test: /\.es6$/, exclude: /node_modules/, loader: 'babel-loader?stage=0&optional=runtime'},
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?stage=0&optional=runtime'},
{ test: /\.less$/, exclude: /node_modules/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")},
{ test: /\.css$/, exclude: /node_modules/, loader: 'style-loader!css-loader' }
];
// dev server for react hot loader
config.devServer = {
publicPath: "/js/",
filename: 'main.js',
contentBase: "./public",
hot: true,
inline: true,
lazy: false,
quiet: true,
noInfo: true,
headers: {"Access-Control-Allow-Origin": "*"},
stats: {colors: true},
host: "0.0.0.0",
port: port
};
module.exports = config;