How to import image in js files? #80
Answered
by
webdiscus
mybardaklar
asked this question in
Q&A
-
How to import image files in JS files? I tried but having problems with path and urls. |
Beta Was this translation helpful? Give feedback.
Answered by
webdiscus
Jun 11, 2023
Replies: 1 comment 10 replies
-
Hello @mybardaklar, try please following working simple example:
module.exports = {
output: {
path: path.join(__dirname, 'dist/'),
publicPath: '', // to import an image in the JS file, the publicPath must not be auto
},
entry: {
index: './src/index.pug',
},
plugins: [
new PugPlugin({
js: {
filename: 'assets/js/[name].[contenthash:8].js',
},
}),
],
module: {
rules: [
{
test: /\.pug$/,
loader: PugPlugin.loader,
},
{
test: /.(png|jpe?g|ico|svg)/,
type: 'asset/resource',
generator: {
filename: 'assets/img/[name].[hash:8][ext]',
},
},
],
},
};
html
head
script(src=require('./main.js') defer="defer")
body
h1 Hello World!
//const img = require('./image.png'); // OK => output filename like assets/img/image.697ef306.png
import img from './image.png'; // OK => output filename like assets/img/image.697ef306.png
console.log('>> image URL:', img); |
Beta Was this translation helpful? Give feedback.
10 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now please try the fixed fork.
It works!
See the changes in:
// ==> load the source image as an object via 'responsive-loa…