Webpack load image inside of HTML - javascript

Somewhere in the middle of my Angular template I have img tag:
<img src="../../images/error.gif" />
Until now I was using raw-loader with this simple configuration:
test: /\.html/,
loader: 'raw'
But after i read this i decide I need a change:
The raw-loader is supposed to turn a text file into a CommonJS module
that exports the file contents as a string – nothing more.
What did I change:
So I changed my raw-loader to html-loader based on this article and this question.
{
test: /\.html$/,
loader: [
"html?" + JSON.stringify({
attrs: ["img:src", "img:ng-src"]
})
]
}
And this: loader
{ test: /.gif$/, loader: "file" }
Based on this and this questions I added publicPath: "/assets" to my webpackconfig.
And changed img tag on <img src=" { require('/assets/logo.png') } " />
My webpackconfig looks like:
webpack({
entry: path.resolve(__dirname, './main.js'),
output: {
path: dir_dist,
filename: 'custom-shared-lib.js',
publicPath: "/assets"
},
module: {
preLoaders: [
{
test: dir_bin,
loader: path.resolve(__dirname, "./my-loader.js"),
query: JSON.stringify(preLoaderQuery)
},
],
loaders: loader
},
plugins: [
// Avoid publishing files when compilation fails
new webpack.NoErrorsPlugin()
],
}, function(err, stats) {
console.log(stats.toString());
});
While variabile loaders are:
[
{
test: /\.js$/,
include: [dir_bin, dir_src],
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
{
test: /\.html$/,
loader: [
"html?" + JSON.stringify({
attrs: ["img:src", "img:ng-src"]
})
]
},
{ test: /.gif$/, loader: "file" }
]
Error:
This error happen while compiling:
Module not found: Error: Cannot resolve 'file' or 'directory' ./ {
require('/assets/error.gif') }
I would be happy for any advice.

Related

Webpack won't compile my SASS with background-image

I have issue compiling my SASS code.
I would like to use a background image, but when I tried this, all my css stopped working.
My SASS file looks like this
#import "~bootstrap/scss/bootstrap";
#import "constants";
#crossroad {
position:relative;
background-image: url("../assets/bg.jpg");
}
My Webpack.config
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: "development",
module: {
rules: [
{
test: /\.(scss|png|jpg)$/,
use: [
{
// Adds CSS to the DOM by injecting a `<style>` tag
loader: 'style-loader'
},
{
// Interprets `#import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader'
},
{
// Loader for webpack to process CSS with PostCSS
loader: 'postcss-loader',
options: {
plugins: function () {
return [
require('autoprefixer')
];
}
}
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'resolve-url-loader'
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'sass-loader'
}
]
}
]
}
};
ERROR MESSAGE:
ERROR in ./src/assets/bg.jpg (./node_modules/css-loader/dist/cjs.js!./node_modules /postcss-loader/src??ref--4-2!./node_modules/resolve-url-loader!./node_modules/sass-loader/dist/cjs.js!./src/assets/bg.jpg)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Invalid CSS after "����": expected "{", was ""
on line 1 of /Users/adrianmindek/Code/PersonalPage/src/assets/bg.jpg
����
^
# ./src/assets/bg.jpg 2:26-236
# ./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/src??ref-- 4-2!./node_modules/resolve-url-loader!./node_modules/sass-loader/dist/cjs.js!./src/scss/app.scss
# ./src/scss/app.scss
# ./src/app.js
I tried to add resolve-url-loader to my webpack config, but nothing changed.
You should handle file using file-loader like this
rules: [{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: ["babel-loader", "eslint-loader"]
},
{
test: /\.(jpe?g|png|gif)$/i,
loader: "file-loader"
},
{
test: /\.(woff|ttf|otf|eot|woff2|svg)$/i,
loader: "file-loader"
}
]
You can view code from here

I have error '] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema"

When I try to use command npm start, I get error
"] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema."
Code: https://next.plnkr.co/edit/hEHTiPYQXQ7POWIH?open=lib%2Fscript.js&deferRun=1
Here is my full configuration code for webpack
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app/app.js',
output: {
path: './dist',
filename: 'app.bundle.js',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.html$/,
use: 'raw-loader'
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
}
]
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
}
]
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
inject: 'body',
hash: true
}),
],
devtool: "#inline-source-map"
}
Error:
Did not detect a `bs-config.json` or `bs-config.js` override file. Using lite-server defaults...
[0] ** browser-sync config **
[0] { injectChanges: false,
[0] files: [ './**/*.{html,htm,css,js}' ],
[0] watchOptions: { ignored: 'node_modules' },
[0] server: { baseDir: './', middleware: [ [Function], [Function] ] } }
] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
[1] - configuration.module has an unknown property 'loaders'. These properties are valid:
[1] object { defaultRules?, exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, strictExportPresence?, strictThisContextOnImports?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp? }
[1] -> Options affecting the normal modules (`NormalModuleFactory`).
[1] - configuration.output.path: The provided value "./dist" is not an absolute path!
[1] -> The output directory as **absolute path** (required).
I found your problem webpack use rules config not loader config so change your code into this
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require("path");
module.exports = {
entry: 'src/app/app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.html$/,
use: 'raw-loader'
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
}
]
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
}
]
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
inject: 'body',
hash: true
}),
],
devtool: "#inline-source-map"
}
Update: move your index.html file into same level of webpack.config.js
I dont see in the document they allow user to change into different path
Please let me know if you still have a problem

Unexpected token given when loading import() with Webpack 4.24.0 or higher

I've been on a dependencies upgrade mission and I have found when upgrading Webpack to 4.24.0 or above I get this failure:
ERROR in ./src/js/components/App.jsx 35:9
Module parse failed: Unexpected token (35:9)
You may need an appropriate loader to handle this file type.
| import ReactModal from 'react-modal';
| var RoomListings = React.lazy(function () {
> return import('./RoomListings.jsx');
| });
| var RoomDetails = React.lazy(function () {
# ./src/js/index.js 3:0-39 6:74-77
# multi ./src/js/index.js
It's failing on the import but what is frustrating is that nothing has changed in either my Webpack or Babel config which are below:
webpack.config.js
module.exports = {
entry: ["./src/js/index.js"],
output: {
path: PATHS.build,
filename: "js/[name].js"
},
devServer: {
contentBase: path.join(__dirname, 'src'),
publicPath: '/'
},
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"},
{ test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.html$/, loader: "html-loader" },
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
{ test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] },
{ test: /\.(png|jp(e*)g|svg)$/, use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
.babelrc
{
"presets": ["#babel/env", "#babel/react"],
"plugins": ["add-react-displayname", "#babel/plugin-syntax-dynamic-import", "emotion"],
"env": {
"test": {
"plugins": ["dynamic-import-node"]
}
}
}
I am assuming something is either missing or misconfigured, but after hours of searching SO and Google, none of the existing answer appear to help.

webpack + babel - react, unexpected token 'import'

I'm trying to make index.js work with es2015.
Before directing me to .babelrc, note that I have added BOTH es2015 and react (to be sure, but there's no react here).
It features
import { default as Logary, Targets, getLogger, build } from 'logary';
And here's .babelrc:
{
"presets": ['es2015', 'react']
}
And webpack.config.js
var webpack = require('webpack'),
HtmlWebpackPlugin = require('html-webpack-plugin'),
path = require('path');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client?reload=true',
'./index.js'
],
output: {
path: path.resolve('./dist'),
filename: '[name].js',
publicPath: '/'
},
loaders: [
{ test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{ test: /\.css$/, loader: "style!css" },
{ test: /\.(png|jpg|jpeg|gif|woff)$/, loader: 'url?limit=8192' },
{ test: /\.(otf|eot|ttf)$/, loader: "file?prefix=font/" },
{ test: /\.svg$/, loader: "file" }
],
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.template.html'
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
resolve: {
extensions: ['', '.js']
}
}
Gives error:
ERROR in ./index.js
Module parse failed: /Users/h/logary-js/examples/webpack/index.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import { default as Logary, Targets, getLogger, build } from 'logary';
|
| // once per site/app
Why is it not handling the import-token?
Your webpack.config.js structure is not correct. Webpack doesn't recognize all your loaders. Specifically, you need to put the loaders property inside of a module section like this:
module: {
loaders: [
{ test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{ test: /\.css$/, loader: "style!css" },
{ test: /\.(png|jpg|jpeg|gif|woff)$/, loader: 'url?limit=8192' },
{ test: /\.(otf|eot|ttf)$/, loader: "file?prefix=font/" },
{ test: /\.svg$/, loader: "file" }
],
}

Use webpack with jade-loader without explicitly requiring assets

I am trying to use Webpack jade-loader in combination with html-loader to be able to omit requires in jade templates + use a path relative to a certain folder. I have tried a few things, none of them worked.
By default jade-loader works when using img(src=require("../../../../assets/images/imac.png") alt="computer"), with the following webpack config:
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/app.js'
],
context: path.resolve(__dirname + "/client"),
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
// placed here so we know that it is done before transpiling
preLoaders: [
{ test: /\.js$/, loader: "eslint-loader", exclude: [/node_modules/, /\.config\.js/, /\.conf\.js/ ] }
],
loaders: [
{ test: /\.html$/, loader: 'raw' },
{ test: /\.jade$/, loader: 'jade-loader' },
{ test: /\.less$/, loader: 'style!css!less' },
{ test: /\.css/, loader: 'style!css' },
{ test: /\.(png|jpg|jpeg|svg)$/, loader: 'file' },
{ test: /\.js$/, loader: 'babel?stage=1', exclude: [/client\/lib/, /node_modules/, /\.spec\.js/] }
]
},
eslint: {
configFile: './.eslintrc'
}
};
If I add the html-loader ({ test: /\.jade$/, loader: 'html-loader!jade-loader' }) which is supposed to require sources by default, I keep getting the 'Error: Module not found'. The console logs all the paths that it tried, all relative to the current working file.
I tried to give it some context, with context: path.resolve(__dirname + "/client"). It didn't work either.
I also tried to combine with the raw loader: raw-loader!html-loader!jade-loader. I don't get the error but the wepback output that is served is not my app at all, but instead something along the lines of:
var jade = require(/......) ....
Do you have any idea ?
Thanks for your help
Had the same Problem.
https://www.npmjs.com/package/pug-html-loader worked for me:
module.exports = {
// your config settings ...
module: [
//your modules...
loaders: [{
include: /\.jade/,
loader: 'pug-html-loader'
}]
]
};
I don't know what do you want. My need is to load a template from a directive (component in 1.5)
angular.module('app').component('myComponent', {
bindings: {},
template: require('./mytemplate.jade')()
});
You can to note that I'm invoking the returned function.

Categories