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.
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?
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" />
How to ouput css file as file.css rather than inline in javascript. My configuration look like below.
{
test: /\.less$/,
loader: "style-loader!css-loader!less-loader"
}
I tested with
"file-loader!css-loader!less-loader" //but the content of the file is not css
You would have to use the extract-text-plugin. You can create one css file for your entire bundle or one for each chunk. For example if you want all your CSS in your bundle moved to a separate file, you would add this to your figuration
module.exports = {
loaders: [
// Extract css files
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
// Optionally extract less files
// or any other compile-to-css language
{
test: /\.less$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")
}
],
plugins: [
new ExtractTextPlugin("[name].css", {
allChunks: true
})
]
}
See stylesheets webpack configuration for more reference
I have a simple index page that uses a handful of js files, including jquery and underscore from a CDN.
To learn, I want to set up requirejs to manage the scripts.
Folder structure:
exampleApp
-js
-foo.js
-main.js
-require.js
-index.html
index, note foo() is a function in foo.js:
<script data-main="js/main" src="js/requirejs-2.1.9.js"></script>
<body>
<button onclick='foo()'>Click me</button>
</body>
main.js:
requirejs.config({
baseUrl: 'js',
paths: {
jquery : '//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js',
underscore : '//cdn.jsdelivr.net/underscorejs/1.5.2/underscore-min.js',
foo : 'foo'
},
shim: {
jquery: {
exports: '$'
},
underscore: {
exports: '_'
}
}
});
requirejs(['jquery', 'underscore', 'foo'], function($, _, foo){
});
In my foo.js, I use jquery using "$" and underscore using "_", so I want to maintain those symbols if possible.