i am not able to render images with pug view template - node.js

doctype html
html(lang="en")
head
meta(charset="UTF-8")
meta(http-equiv="X-UA-Compatible", content="IE=edge")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
title Document
body
div
img(src='./tree.jpg' alt='login' style='width:100px; height:100px;')
#form
form(action="/" method="post")
label(for="name") name
input(type="text" name="name" id="name" placeholder="okay")
input(type="submit" value="dingoo")

Install the pug-loader:
npm install #webdiscus/pug-loader --save-dev
In webpack config module add following rules:
module.exports = {
// ...
module: {
rules: [
// ...
{
test: /\.pug$/,
loader: '#webdiscus/pug-loader'
},
{
test: /\.(png|jpg|jpeg|svg|ico)/,
type: 'asset/resource',
generator: {
filename: 'assets/images/[name].[hash:8][ext]',
},
},
]
},
}
In pug use require() for image:
img(src=require('./path/to/tree.jpg)')
Generated HTML:
<img src="/assets/images/tree.23fe5de2.jpg">
This works fine with the #webdiscus/pug-loader.

Related

Using Mocked Service Worker (msw) with #web/test-runner

I am trying to setup msw with #web/test-runner (and playwright). The problem is that I don't know how the mockServiceWorker.js can be picked up by the test runner (which uses browser, not nodejs like jest). There is an example with karma:
https://github.com/mswjs/examples/tree/master/examples/with-karma, probably I have to do something similar but I have no idea where to start. Any hints are welcome.
I am not sure if it is important, but let me share my web.test-runner.config.js
import vite from 'vite-web-test-runner-plugin'
import { playwrightLauncher } from '#web/test-runner-playwright';
export default {
plugins: [ vite() ],
coverageConfig: {
include: [ 'src/**/*.{svelte,js,jsx,ts,tsx}' ]
},
browsers: [
playwrightLauncher({ product: 'chromium' })
],
testRunnerHtml: testFramework => `
<!DOCTYPE html>
<html>
<head>
<script type="module">
window.global = window;
window.process = { env: {} };
</script>
<script type="module" src="${testFramework}"></script>
</head>
</html>
};
and my test command
"test": "web-test-runner \"test/**/*.test.ts\"",

Loading SVG with Webpack5

I am trying to migrate our package from Webpack 4 to Webpack 5 but have issue with svg loading.
Previously, we use HtmlWebpackInlineSourcePlugin and raw-loader in our webpack config.
plugins: [
new HtmlWebpackPlugin({
inlineSource: '.(js|css)$',
template: <>,
filename: <>,
inject: 'head',
}),
new HtmlWebpackInlineSourcePlugin(),
]
...
module: {
rules: [
{
test: /\.(svg)$/,
loader: 'raw-loader',
},
Here is the html file:
<button id="button" type="button">
${require('../../node_modules/open-iconic<link to svg>').default}
</button>
Expected output:
<button id="button" type="button">
<svg ...>
<path/>
</svg>
</button>
Both of HtmlWebpackInlineSourcePlugin and raw-loader are deprecated in Webpack 5. For HtmlWebpackInlineSourcePlugin, I replaced with InlineChunkHtmlPlugin from react-dev-utils and for raw-loader I tried to follow the asset module guide but it did not work (the import statement is not updated).
plugins: [
new HtmlWebpackPlugin({
inlineSource: '.(js|css)$',
template: <>,
filename: <>,
inject: 'head',
}),
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [new RegExp(`<output name>`)]),,
]
...
module: {
rules: [
{
test: /\.(svg)$/,
type: 'asset/source'
},
Does anyone know if I miss anything?

Why doesn't the image from the external link work in gatsby?

Excuse me, please, I am just learning. In some gatsby templates I can insert as Image - an image from a URL and in some templates Image don't want to display it.
What does it depend on and how to edit the code to make the url work? (My knowledge about graphql is rather basic)
this is the code for the blog template:
/** #jsx jsx */
import { jsx } from 'theme-ui'
import { Link, graphql } from "gatsby"
import Img from "gatsby-image"
import { RiArrowRightLine, RiArrowLeftLine } from "react-icons/ri"
import Layout from "../components/layout"
import SEO from '../components/seo';
const styles = {
'article blockquote': {
'background-color': 'cardBg'
},
pagination: {
'a': {
color: 'muted',
'&.is-active': {
color: 'text'
},
'&:hover': {
color: 'text'
}
}
}
}
const Pagination = (props) => (
<div
className="pagination -post"
sx={styles.pagination}
>
<ul>
{(props.previous && props.previous.frontmatter.template === 'blog-post') && (
<li>
<Link to={props.previous.frontmatter.slug} rel="prev">
<p
sx={{
color: 'muted'
}}
>
<span className="icon -left"><RiArrowLeftLine/></span> Previous</p>
<span className="page-title">{props.previous.frontmatter.title}</span>
</Link>
</li>
)}
{(props.next && props.next.frontmatter.template === 'blog-post') && (
<li>
<Link to={props.next.frontmatter.slug} rel="next">
<p
sx={{
color: 'muted'
}}
>Next <span className="icon -right"><RiArrowRightLine/></span></p>
<span className="page-title">{props.next.frontmatter.title}</span>
</Link>
</li>
)}
</ul>
</div>
)
const Post = ({ data, pageContext }) => {
const { markdownRemark } = data // data.markdownRemark holds your post data
const { frontmatter, html, excerpt } = markdownRemark
const Image = frontmatter.featuredImage ? frontmatter.featuredImage.childImageSharp.fluid : ""
const { previous, next } = pageContext
let props = {
previous,
next
}
return (
<Layout className="page">
<SEO
title={frontmatter.title}
description={frontmatter.description ? frontmatter.description : excerpt}
image={Image}
article={true}
/>
<article className="blog-post">
<header className="featured-banner">
<section className="article-header">
<h1>{frontmatter.title}</h1>
<time>{frontmatter.date}</time>
</section>
{Image ? (
<Img
fluid={Image}
objectFit="cover"
objectPosition="50% 50%"
alt={frontmatter.title + ' - Featured image'}
className="featured-image"
/>
) : ""}
</header>
<div
className="blog-post-content"
dangerouslySetInnerHTML={{ __html: html }}
/>
</article>
{(previous || next) && (
<Pagination {...props} />
)}
</Layout>
)
}
export default Post
export const pageQuery = graphql`
query BlogPostQuery($id: String!) {
markdownRemark(
id: { eq: $id }
) {
id
html
excerpt(pruneLength: 148)
frontmatter {
date(formatString: "MMMM DD, YYYY")
slug
title
description
featuredImage {
childImageSharp {
fluid(maxWidth: 1980, maxHeight: 768, quality: 80, srcSetBreakpoints: [350, 700, 1050, 1400]) {
...GatsbyImageSharpFluid
...GatsbyImageSharpFluidLimitPresentationSize
}
sizes {
src
}
}
}
}
}
}
`
typical post:
---
template: blog-post
title: my title
slug: /plant/bud
date: 2020-05-13 12:37
description: abc
featuredImage: /assets/screen-post-hixmjdah9xhoo-unsplash.jpg (but online image from imgurl png doesnt work)
---
post nr 1
edited ///
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/static/assets/`,
name: `assets`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/content/`,
name: `content`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-transformer-remark`,
options: {
gfm: true,
plugins: [
netlifyCmsPaths,
`gatsby-remark-reading-time`,
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 1024,
showCaptions: true,
linkImagesToOriginal: false,
tracedSVG: true,
loading: "lazy",
},
},
`gatsby-remark-responsive-iframe`,
{
resolve: `gatsby-remark-prismjs`,
options: {
classPrefix: "language-",
inlineCodeMarker: null,
aliases: {},
showLineNumbers: false,
noInlineHighlight: false,
// By default the HTML entities <>&'" are escaped.
// Add additional HTML escapes by providing a mapping
// of HTML entities and their escape value IE: { '}': '{' }
escapeEntities: {},
},
},
],
},
},
In Gatsby, you can insert images from external sources using the standard HTML <img> tag with the src property:
<img src="https://via.placeholder.com/150" alt="Alt text" width="500" height="600">
If you want to keep the benefits of gatsby-image across the external (or online) images, you should need to use some dependencies to achieve lazy loading and other features.
However, to use gatsby-image you need to allow Gatsby and the inferred GraphQL schema to use their transformers (gatsby-transformer-sharp and sharps (gatsby-plugin-sharp) across with the filesystem (gatsby-source-filesystem) or in other words, Gatsby needs to have access to the images that needs to parse to create a valid queryable GraphQL schema, that will be consumed with the gatsby-image.
In addition, you need to specify the folder of your project where those images belong (setting the filesystem):
const path = require(`path`)
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: path.join(__dirname, `src`, `images`),
},
},
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
],
}
Once the filesystem is set and the images are processed, a GraphQL node is created, and you are allowed to use the fragments like the one you've provided:
featuredImage {
childImageSharp {
fluid(maxWidth: 1980, maxHeight: 768, quality: 80, srcSetBreakpoints: [350, 700, 1050, 1400]) {
...GatsbyImageSharpFluid
...GatsbyImageSharpFluidLimitPresentationSize
}
sizes {
src
}
}
}
Since the external images can't be directly processed by Gatsby, they can't be used with gatsby-image. Depending on the source of those images, some plugins allow you to keep using gatsby-image from external sources (usually from CMSs like Contentful and others).
You can check for further documentation in Working with images docs.
Update (01/06/2021)
In the last Gatsby version (v2.30) they've added a new experimental feature, still in beta to support external images in a <StaticImage> component. To enable it, just upgrade to the latest Gatsby version (via npm or yarn) and add the following flags in your running scripts:
GATSBY_EXPERIMENTAL_REMOTE_IMAGES=1 gatsby develop
GATSBY_EXPERIMENTAL_REMOTE_IMAGES=1 gatsby build
You can then pass absolute URLs to StaticImage:
<StaticImage src="https://placekitten.com/400/400" alt="Kittin" />

Does the url-loader plugin inline URLs in <img> tags, how?

Udate:
Although I haven't been able to find out whether this is a feature or a bug. It seems url-loader can't process the assets used in the Svelte component unless those are loaded via require. So I would like to know what's the more common or recommended way to load/preprocess, using Webpack 4, a Svelte component source so that all image assets used in src/url in HTML tags and CSS styles get inlined, i.e. converted to use the embedded base64 data in the HTML or CSS output files.
Original Question
I want to have a tag <img src="./assets/logo.png"> in a svelte component to be converted to <img src="data:image/png;base64,iV...CC"> in the output, but if I add url-loader to my webpack.config.js file like so:
module: {
rules: [
//...
{
test: /logo.png/,
loader: (process.stdout.write("!!!\n"), 'url-loader')
}
The URL in src does still appear as "./assets/logo.png" in the output even is the console shows "!!!" during the webpack build process with no errors, why is url-loader not making the conversion? The file logo.png is about 3KB in size, but I'm not sure is that's the problem since it's small in size.
The image is being used here like so:
<div id="app">
{#if path === '/'}
<span on:click={navigateToSettings} id="menu"><div class="hamburger" /></span>
{/if}
{#if path === '/settings' && isStored()}
<span on:click={cancel} id="menu"><div class="close" /></span>
{/if}
<img class='logo' src='./assets/img/logo.png' alt='Spark'>
{#if connected}
<span id="status" class="green">•</span>
{:else}
<span id="status" class="red">•</span>
{/if}
<div id="content">
<RouterView />
</div>
</div>
And I'm adding the url-loader rule here before the rule for audio files:
module: {
rules: [
//...
{
test: /logo.png/,
loader: (process.stdout.write("!!!\n"), 'url-loader')
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader'
},
If you use webpack and url-loader with any of modern frontend frameworks it is a common practice to use images via require.
Example from react world:
import iconMore from “../path_to_image/name_of_image.jpg”;
const Icon = (props) => {
return <img src={iconMore} />
}
for more examples please see this question.
Also I found svelte-assets-preprocessor - you can use it in pair with url-loader without direct require, but under the hood it is the same technique:
module: {
rules: [
...
{
test: /\.(png|svg|jpg|gif)$/,
loader: 'file-loader',
options: {
outputPath: 'images',
}
},
{
test: /\.(html|svelte)$/,
exclude: /node_modules/,
use: {
loader: 'svelte-loader',
options: {
preprocess: require('svelte-assets-preprocessor')({ /* options */ exclude: [ (attr) => !/\.(png|svg|jpg|gif)$/.test(attr)} ])
},
},
},
...
]
}
Input
<img src="./example.png">
Output
<script>
import ___ASSET___1 from './example.png';
</script>
<img src="{___ASSET___1}">

AngularJS2 : Getting 404 Not Found in the models folder even though file is there

I have the following app structure:
I want my application where each page like "Create.cshtml" will
bootstrap(Scripts/app/project/create/app.projects.create-boot.ts)
and
load the application (/app.projects.create.ts).
I also have a models folder which will hold all my models and will be shared.
serviceline.js(Scripts/models/serviceline.ts)
app.projects.create-boot.ts:
/// <reference path="../../../../node_modules/angular2/typings/browser.d.ts" />
import {bootstrap} from 'angular2/platform/browser'
import {AppProjectsCreateComponent} from './app.projects.create'
import {ServiceLine} from '../../../models/serviceline';
bootstrap(AppProjectsCreateComponent, [ServiceLine]);
app.projects.create.ts:
import {Component} from 'angular2/core';
import {ServiceLine} from '../../../models/serviceline';
#Component({
selector: 'project-create',
templateUrl: '../../appScripts/app/projects/create/app.projects.create.html'
})
export class AppProjectsCreateComponent {
name = "max";
serviceLines: ServiceLine[];
constructor() {
//this.serviceLines = [ new ServiceLine(1, "Name Test") ];
}
}
serviceLine.ts
export class ServiceLine {
ServiceLineId: number;
Name: string
constructor(serviceLineId: number, name: string) {
this.ServiceLineId = serviceLineId;
this.Name = name;
}
}
Create.cshtml:
#*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*#
#section head{
<script src="~/lib/es6-shim.min.js"></script>
<script src="~/lib/system-polyfills.js"></script>
<script src="~/lib/shims_for_IE.js"></script>
<script src="~/lib/angular2-polyfills.js"></script>
<script src="~/lib/system.js"></script>
<script src="~/lib/rx.js"></script>
<script src="~/lib/angular2.dev.js"></script>
<!-- 2. Configure SystemJS -->
}
#{
<script>
System.config({
map: {
appScripts: '../appScripts/app/projects/create'
},
packages: {
appScripts: {
defaultExtension: 'js'
}
}
});
System.import('appScripts/app.projects.create-boot')
.then(null, console.error.bind(console));
</script>
}
<br />
<project-create></project-create>
Everything was loading find until I added ServiceLine[] in the app.projects.create.ts file.
Here is the error:
What am I missing? Why can't Angular find the serviceLine.js.
Edit: Change the map field.
<script>
System.config({
map: {
appScripts: '../appScripts' //Change Here
},
packages: {
appScripts: {
defaultExtension: 'js'
}
}
});
System.import('appScripts/app/projects/create/app.projects.create-boot') //Change Here
.then(null, console.error.bind(console));
</script>
The problem is that your service file isn't targetted with your SystemJS configuration because of the map block.
So SystemJS doesn't append the JS extension. I would remove the map block:
<script>
System.config({
/* map: {
appScripts: '../appScripts/app/projects/create'
}, */
packages: {
appScripts: {
defaultExtension: 'js'
}
}
});
System.import('appScripts/app/projects/create/app.projects.create-boot')
.then(null, console.error.bind(console));
</script>
and update accordingly the path in your imports.
With this configuration the "model" will be token into account. Your configuration would only work if your "model" folder was under the "create" one.

Resources