Compare commits
2 commits
main
...
wip-compon
Author | SHA1 | Date | |
---|---|---|---|
|
59728dd64a | ||
|
653b23082f |
28 changed files with 120 additions and 505 deletions
17
.changeset/strange-kids-sing.md
Normal file
17
.changeset/strange-kids-sing.md
Normal file
|
@ -0,0 +1,17 @@
|
|||
---
|
||||
'astro': minor
|
||||
---
|
||||
|
||||
[BREAKING CHANGE] change Astro.fetchContent() to a runtime API. This makes two breaking changes to the existing Astro.fetchContent() API:
|
||||
|
||||
1. The method is now async. Previously, it was synchronous.
|
||||
2. The method now takes in an `import.meta.glob()` argument. Previous, it took a string.
|
||||
|
||||
Example change to make to your code:
|
||||
|
||||
```diff
|
||||
- let allPosts = Astro.fetchContent('../pages/posts/*.md');
|
||||
+ let allPosts = await Astro.fetchContent(import.meta.glob('../pages/posts/*.md'));
|
||||
```
|
||||
|
||||
An error will throw if you use the deprecated syntax.
|
|
@ -40,7 +40,7 @@ const { collection } = Astro.props;
|
|||
|
||||
// Define a `createCollection` function.
|
||||
export async function createCollection() {
|
||||
const allPosts = Astro.fetchContent('../posts/*.md'); // fetch local posts.
|
||||
const allPosts = await Astro.fetchContent(import.meta.glob('../posts/*.md')); // fetch local posts.
|
||||
allPosts.sort((a, b) => a.title.localeCompare(b.title)); // sort by title.
|
||||
return {
|
||||
// Because you are not doing anything more than simple pagination,
|
||||
|
|
|
@ -9,12 +9,16 @@ The `Astro` global is available in all contexts in `.astro` files. It has the fo
|
|||
|
||||
### `Astro.fetchContent()`
|
||||
|
||||
`Astro.fetchContent()` is a way to load local `*.md` files into your static site setup. You can either use this on its own, or within [Astro Collections][docs-collections].
|
||||
`Astro.fetchContent()` is a way to load local Markdown files in Astro. You can use this to generate pages based on your site content, for things like [paginated collections][docs-collections] or a single page that lists all posts on your site.
|
||||
|
||||
This leverages `import.meta.glob` in Snowpack to fetch the local files.
|
||||
|
||||
```jsx
|
||||
// ./src/components/my-component.astro
|
||||
---
|
||||
const data = Astro.fetchContent('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md
|
||||
// Example: ./src/components/my-component.astro
|
||||
// - `import.meta.glob('../pages/post/*.md')` returns references to all markdown posts.
|
||||
// - `Astro.fetchContent()` loads the referenced markdown files, and returns the result.
|
||||
const posts = await Astro.fetchContent(import.meta.glob('../pages/post/*.md'));
|
||||
---
|
||||
|
||||
<div>
|
||||
|
@ -28,24 +32,25 @@ const data = Astro.fetchContent('../pages/post/*.md'); // returns an array of po
|
|||
</div>
|
||||
```
|
||||
|
||||
`.fetchContent()` only takes one parameter: a relative URL glob of which local files you’d like to import. Currently only `*.md` files are supported. It’s synchronous, and returns an array of items of type:
|
||||
Any non-markdown posts will be ignored. A successful call returns a Promise, which resolves to array of items of the following type:
|
||||
|
||||
```js
|
||||
{
|
||||
/** frontmatter from the post.. example frontmatter:
|
||||
/** Markdown file frontmatter: */
|
||||
title: '',
|
||||
tag: '',
|
||||
date: '',
|
||||
image: '',
|
||||
author: '',
|
||||
description: '',
|
||||
**/
|
||||
/** astro metadata: **/
|
||||
astro: {
|
||||
headers: [], // an array of h1...h6 elements in the markdown file
|
||||
source: '' // raw source of the markdown file
|
||||
html: '' // rendered HTML of the markdown file
|
||||
},
|
||||
url: '' // the rendered path
|
||||
/** the file's web URL (if it is a page) */
|
||||
url: ''
|
||||
}[]
|
||||
```
|
||||
|
||||
|
|
|
@ -15,7 +15,7 @@ import authorData from '../data/authors.json';
|
|||
let { collection } = Astro.props;
|
||||
export async function createCollection() {
|
||||
/** Load posts */
|
||||
let allPosts = Astro.fetchContent('./post/*.md');
|
||||
let allPosts = await Astro.fetchContent(import.meta.glob('./post/*.md'));
|
||||
let allAuthors = new Set();
|
||||
|
||||
/** Loop through all posts, gather all authors */
|
||||
|
|
|
@ -16,7 +16,7 @@ export async function createCollection() {
|
|||
return {
|
||||
/** Load posts, sort newest -> oldest */
|
||||
async data() {
|
||||
let allPosts = Astro.fetchContent('./post/*.md');
|
||||
let allPosts = await Astro.fetchContent(import.meta.glob('./post/*.md'));
|
||||
allPosts.sort((a, b) => new Date(b.date) - new Date(a.date));
|
||||
return allPosts;
|
||||
},
|
||||
|
|
|
@ -14,7 +14,7 @@ let title = 'Don’s Blog';
|
|||
let description = 'An example blog on Astro';
|
||||
|
||||
// Data Fetching: List all Markdown posts in the repo.
|
||||
let allPosts = Astro.fetchContent('./post/*.md');
|
||||
let allPosts = await Astro.fetchContent(import.meta.glob('./post/*.md'));
|
||||
allPosts.sort((a, b) => new Date(b.date) - new Date(a.date));
|
||||
|
||||
// Full Astro Component Syntax:
|
||||
|
|
|
@ -13,7 +13,8 @@ let description = 'The perfect starter for your perfect blog.';
|
|||
let permalink = 'https://example.com/';
|
||||
|
||||
// Data Fetching: List all Markdown posts in the repo.
|
||||
let allPosts = Astro.fetchContent('./posts/*.md');
|
||||
let allPosts = await Astro.fetchContent(import.meta.glob('../pages/posts/*.md'));
|
||||
console.log(allPosts)
|
||||
allPosts = allPosts.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate));
|
||||
|
||||
// Full Astro Component Syntax:
|
||||
|
|
|
@ -1,9 +1,16 @@
|
|||
---
|
||||
const { title = 'Jeanine White: Personal Site' } = Astro.props;
|
||||
---
|
||||
export interface Props {
|
||||
title: string;
|
||||
description?: string[];
|
||||
}
|
||||
|
||||
export function __state({props}: {props: Props}) {
|
||||
return {description: props.description || 'This is the default site descrition.'};
|
||||
}
|
||||
---
|
||||
<meta charset="UTF-8">
|
||||
<title>{title}</title>
|
||||
<title>{$props.title}</title>
|
||||
<meta name="description" content={$state.description}>
|
||||
<link rel="stylesheet" type="text/css" href="/global.css">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@200;400;700;900&display=swap" rel="stylesheet">
|
|
@ -3,12 +3,10 @@ import MainHead from '../components/MainHead.astro';
|
|||
import Button from '../components/Button/index.jsx';
|
||||
import Footer from '../components/Footer/index.jsx';
|
||||
import Nav from '../components/Nav/index.jsx';
|
||||
|
||||
const { content } = Astro.props;
|
||||
---
|
||||
<html>
|
||||
<head>
|
||||
<MainHead title={content.title} />
|
||||
<MainHead title={$props.content.title} />
|
||||
<style lang="scss">
|
||||
.hero {
|
||||
padding: 8rem;
|
||||
|
|
|
@ -8,7 +8,7 @@ let { collection } = Astro.props;
|
|||
export async function createCollection() {
|
||||
return {
|
||||
async data() {
|
||||
const projects = Astro.fetchContent('./project/*.md');
|
||||
const projects = await Astro.fetchContent(import.meta.glob('./project/*.md'));
|
||||
projects.sort((a, b) => new Date(b.published_at) - new Date(a.published_at));
|
||||
return projects.filter(({ published_at }) => !!published_at);
|
||||
}
|
||||
|
|
|
@ -1,245 +1,12 @@
|
|||
---
|
||||
// Component Imports
|
||||
import MainHead from '../components/MainHead.astro';
|
||||
import Button from '../components/Button/index.jsx';
|
||||
import Nav from '../components/Nav/index.jsx';
|
||||
import Footer from '../components/Footer/index.jsx';
|
||||
import PorfolioPreview from '../components/PortfolioPreview/index.jsx';
|
||||
|
||||
// Data Fetching: List all Markdown posts in the repo.
|
||||
const projects = Astro.fetchContent('./project/**/*.md');
|
||||
const featuredProject = projects[0];
|
||||
|
||||
// Full Astro Component Syntax:
|
||||
// https://github.com/snowpackjs/astro/blob/main/docs/core-concepts/astro-components.md
|
||||
---
|
||||
<html>
|
||||
<head>
|
||||
<MainHead title="Jeanine White: Personal Site" />
|
||||
<style lang="scss">
|
||||
$w-s: 750px;
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
|
||||
@media (min-width: $w-s) {
|
||||
height: 45vw;
|
||||
}
|
||||
}
|
||||
|
||||
.img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.gradient,
|
||||
.gradient2 {
|
||||
background-image: url('/assets/mesh-gradient.jpg');
|
||||
pointer-events: none;
|
||||
mix-blend-mode: screen;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.gradient2 {
|
||||
mix-blend-mode: multiply;
|
||||
}
|
||||
|
||||
.overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding-left: 2rem;
|
||||
|
||||
@media (min-width: $w-s) {
|
||||
padding-left: 4rem;
|
||||
}
|
||||
}
|
||||
|
||||
.title {
|
||||
font-weight: 900;
|
||||
font-size: var(--f-u8);
|
||||
margin-bottom: 0.5rem;
|
||||
margin-top: 0;
|
||||
|
||||
@media (min-width: $w-s) {
|
||||
font-size: var(--f-u12);
|
||||
}
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-gap: 2rem;
|
||||
|
||||
@media (min-width: 1200px) {
|
||||
grid-template-columns: 2fr 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-weight: 700;
|
||||
font-size: var(--f-u8);
|
||||
margin-top: 4rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.role {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
font-weight: 900;
|
||||
color: var(--t-bg);
|
||||
background-color: var(--t-fg);
|
||||
padding: 0.25em 0.5em;
|
||||
z-index: 2;
|
||||
|
||||
@media (min-width: $w-s) {
|
||||
font-size: var(--f-u3);
|
||||
}
|
||||
|
||||
+ .role {
|
||||
margin-left: 1em;
|
||||
}
|
||||
|
||||
&:nth-of-type(1) {
|
||||
.invert {
|
||||
background-color: var(--c-pink);
|
||||
}
|
||||
}
|
||||
|
||||
&:nth-of-type(2) {
|
||||
.invert {
|
||||
background-color: var(--c-blue);
|
||||
}
|
||||
}
|
||||
|
||||
&:nth-of-type(3) {
|
||||
.invert {
|
||||
background-color: var(--c-green);
|
||||
}
|
||||
}
|
||||
|
||||
&:hover {
|
||||
.invert {
|
||||
clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.invert {
|
||||
position: absolute;
|
||||
color: var(--t-fg);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
top: 0;
|
||||
left: 0;
|
||||
pointer-events: none;
|
||||
clip-path: polygon(0% 100%, 100% 100%, 100% 200%, 0% 200%);
|
||||
transition: clip-path cubic-bezier(0.4, 0, 0.5, 1) 150ms;
|
||||
}
|
||||
|
||||
.desc {
|
||||
font-size: var(--f-u2);
|
||||
margin-top: 1.5rem;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
display: block;
|
||||
font-weight: 400;
|
||||
font-size: var(--f-d6);
|
||||
letter-spacing: -0.0625em;
|
||||
}
|
||||
|
||||
.bio {
|
||||
line-height: 2;
|
||||
margin-bottom: 2rem;
|
||||
|
||||
> span:first-of-type {
|
||||
line-height: 1;
|
||||
margin-bottom: 0.5em;
|
||||
display: block;
|
||||
font-weight: 700;
|
||||
font-size: var(--f-u4);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<Nav />
|
||||
<header class="hero">
|
||||
<img
|
||||
width="1600"
|
||||
height="1131"
|
||||
class="img"
|
||||
src="https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=1200&q=75"
|
||||
srcSet="https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=1200&q=75 800w,
|
||||
https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=1200&q=75 1200w,
|
||||
https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=1600&q=75 1600w,
|
||||
https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?w=2400&q=75 2400w,"
|
||||
sizes="(max-width: 800px) 800px, (max-width: 1200px) 1200px, (max-width: 1600px) 1600px, (max-width: 2400px) 2400px, 1200px"
|
||||
/>
|
||||
<div class="gradient" />
|
||||
<div class="gradient2" />
|
||||
<div class="overlay">
|
||||
<h1 class="title">
|
||||
<small class="subtitle">The personal site of </small>Jeanine White
|
||||
</h1>
|
||||
<div>
|
||||
<span class="role">
|
||||
👩💻 Developer <span class="invert">👩💻 Developer</span>
|
||||
</span>
|
||||
<span class="role">
|
||||
🎤 Speaker <span class="invert">🎤 Speaker</span>
|
||||
</span>
|
||||
<span class="role">
|
||||
✏️ Writer <span class="invert">✏️ Writer</span>
|
||||
</span>
|
||||
</div>
|
||||
<p class="desc">Lover of dogs, roadtrips, and poetry.</p>
|
||||
</div>
|
||||
</header>
|
||||
<main class="wrapper mt4 mb4">
|
||||
<div class="grid">
|
||||
<div class="section">
|
||||
<h3 class="sectionTitle">Selected Work</h3>
|
||||
<PorfolioPreview project={featuredProject} />
|
||||
<div class="tac mt4">
|
||||
<a href="/projects">
|
||||
<Button>View All</Button>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h3 class="sectionTitle">About me</h3>
|
||||
<p class="bio">
|
||||
<span>Hello!</span> I’m Jeanine, and this is my website. It was made using{' '}
|
||||
<a href="https://github.com/snowpackjs/astro" target="_blank" rel="nofollow">
|
||||
Astro
|
||||
</a>
|
||||
, a new way to build static sites. This is just an example template for you to modify.
|
||||
</p>
|
||||
<p>
|
||||
<a href="/about">Read more</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<Footer />
|
||||
Test
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
"build": "yarn build:core",
|
||||
"build:all": "lerna run build",
|
||||
"build:one": "lerna run build --scope",
|
||||
"build:core": "lerna run build --scope astro --scope @astrojs/parser --scope @astrojs/markdown-support --scope create-astro",
|
||||
"build:core": "lerna run build --scope astro --scope @astrojs/parser --scope @astrojs/markdown-support",
|
||||
"build:vscode": "lerna run build --scope astro-languageserver --scope astro-vscode --scope @astrojs/parser",
|
||||
"dev:vscode": "lerna run dev --scope astro-languageserver --scope astro-vscode --scope @astrojs/parser --parallel --stream",
|
||||
"format": "prettier -w \"**/*.{js,jsx,ts,tsx,md,json}\"",
|
||||
|
|
|
@ -170,7 +170,7 @@ For fetching from a remote API, use a native JavaScript `fetch()` ([docs][fetch-
|
|||
const remoteData = await fetch('https://api.mysite.com/v1/people').then((res) => res.json());
|
||||
|
||||
// Example 2: load local markdown files
|
||||
const localData = Astro.fetchContent('../post/*.md');
|
||||
const localData = await Astro.fetchContent(import.meta.glob('../post/*.md'));
|
||||
---
|
||||
```
|
||||
|
||||
|
|
|
@ -51,7 +51,6 @@
|
|||
"@babel/code-frame": "^7.12.13",
|
||||
"@babel/generator": "^7.13.9",
|
||||
"@babel/parser": "^7.13.15",
|
||||
"@babel/traverse": "^7.13.15",
|
||||
"@snowpack/plugin-postcss": "^1.4.3",
|
||||
"@snowpack/plugin-sass": "^1.4.0",
|
||||
"acorn": "^7.4.0",
|
||||
|
|
|
@ -1,58 +0,0 @@
|
|||
import path from 'path';
|
||||
import glob from 'tiny-glob/sync.js';
|
||||
import slash from 'slash';
|
||||
|
||||
/**
|
||||
* Handling for import.meta.glob and import.meta.globEager
|
||||
*/
|
||||
interface GlobOptions {
|
||||
namespace: string;
|
||||
filename: string;
|
||||
}
|
||||
|
||||
interface GlobResult {
|
||||
/** Array of import statements to inject */
|
||||
imports: Set<string>;
|
||||
/** Replace original code with */
|
||||
code: string;
|
||||
}
|
||||
|
||||
/** General glob handling */
|
||||
function globSearch(spec: string, { filename }: { filename: string }): string[] {
|
||||
try {
|
||||
const cwd = path.dirname(filename);
|
||||
let found = glob(spec, { cwd, filesOnly: true });
|
||||
if (!found.length) {
|
||||
throw new Error(`No files matched "${spec}" from ${filename}`);
|
||||
}
|
||||
return found.map((f) => slash(f[0] === '.' ? f : `./${f}`));
|
||||
} catch (err) {
|
||||
throw new Error(`No files matched "${spec}" from ${filename}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Astro.fetchContent() */
|
||||
export function fetchContent(spec: string, { namespace, filename }: GlobOptions): GlobResult {
|
||||
let code = '';
|
||||
const imports = new Set<string>();
|
||||
const importPaths = globSearch(spec, { filename });
|
||||
|
||||
// gather imports
|
||||
importPaths.forEach((importPath, j) => {
|
||||
const id = `${namespace}_${j}`;
|
||||
imports.add(`import { __content as ${id} } from '${importPath}';`);
|
||||
|
||||
// add URL if this appears within the /pages/ directory (probably can be improved)
|
||||
const fullPath = path.resolve(path.dirname(filename), importPath);
|
||||
|
||||
if (fullPath.includes(`${path.sep}pages${path.sep}`)) {
|
||||
const url = importPath.replace(/^\./, '').replace(/\.md$/, '');
|
||||
imports.add(`${id}.url = '${url}';`);
|
||||
}
|
||||
});
|
||||
|
||||
// generate replacement code
|
||||
code += `${namespace} = [${importPaths.map((_, j) => `${namespace}_${j}`).join(',')}];\n`;
|
||||
|
||||
return { imports, code };
|
||||
}
|
|
@ -12,10 +12,7 @@ import { walk, asyncWalk } from 'estree-walker';
|
|||
import _babelGenerator from '@babel/generator';
|
||||
import babelParser from '@babel/parser';
|
||||
import { codeFrameColumns } from '@babel/code-frame';
|
||||
import * as babelTraverse from '@babel/traverse';
|
||||
import { error, warn, parseError } from '../../logger.js';
|
||||
import { fetchContent } from './content.js';
|
||||
import { isFetchContent } from './utils.js';
|
||||
import { yellow } from 'kleur/colors';
|
||||
import { isComponentTag, isCustomElementTag, positionAt } from '../utils.js';
|
||||
import { renderMarkdown } from '@astrojs/markdown-support';
|
||||
|
@ -26,8 +23,6 @@ import { nodeBuiltinsSet } from '../../node_builtins.js';
|
|||
import { readFileSync } from 'fs';
|
||||
import { pathToFileURL } from 'url';
|
||||
|
||||
const traverse: typeof babelTraverse.default = (babelTraverse.default as any).default;
|
||||
|
||||
// @ts-ignore
|
||||
const babelGenerator: typeof _babelGenerator = _babelGenerator.default;
|
||||
const { transformSync } = esbuild;
|
||||
|
@ -322,11 +317,9 @@ function compileModule(ast: Ast, module: Script, state: CodegenState, compileOpt
|
|||
const componentImports: ImportDeclaration[] = [];
|
||||
const componentProps: VariableDeclarator[] = [];
|
||||
const componentExports: ExportNamedDeclaration[] = [];
|
||||
const contentImports = new Map<string, { spec: string; declarator: string }>();
|
||||
|
||||
let script = '';
|
||||
let propsStatement = '';
|
||||
let contentCode = ''; // code for handling Astro.fetchContent(), if any;
|
||||
let createCollection = ''; // function for executing collection
|
||||
|
||||
if (module) {
|
||||
|
@ -387,37 +380,11 @@ function compileModule(ast: Ast, module: Script, state: CodegenState, compileOpt
|
|||
break;
|
||||
}
|
||||
case 'VariableDeclaration': {
|
||||
// Support frontmatter-defined components
|
||||
for (const declaration of node.declarations) {
|
||||
// only select Astro.fetchContent() calls for more processing,
|
||||
// otherwise just push name to declarations
|
||||
if (!isFetchContent(declaration)) {
|
||||
if (declaration.id.type === 'Identifier') {
|
||||
state.declarations.add(declaration.id.name);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// remove node
|
||||
body.splice(i, 1);
|
||||
|
||||
// a bit of munging
|
||||
let { id, init } = declaration;
|
||||
if (!id || !init || id.type !== 'Identifier') continue;
|
||||
if (init.type === 'AwaitExpression') {
|
||||
init = init.argument;
|
||||
const shortname = path.posix.relative(compileOptions.astroConfig.projectRoot.pathname, state.filename);
|
||||
warn(compileOptions.logging, shortname, yellow('awaiting Astro.fetchContent() not necessary'));
|
||||
}
|
||||
if (init.type !== 'CallExpression') continue;
|
||||
|
||||
// gather data
|
||||
const namespace = id.name;
|
||||
|
||||
if ((init as any).arguments[0].type !== 'StringLiteral') {
|
||||
throw new Error(`[Astro.fetchContent] Only string literals allowed, ex: \`Astro.fetchContent('./post/*.md')\`\n ${state.filename}`);
|
||||
}
|
||||
const spec = (init as any).arguments[0].value;
|
||||
if (typeof spec === 'string') contentImports.set(namespace, { spec, declarator: node.kind });
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
@ -466,64 +433,7 @@ const { ${props.join(', ')} } = Astro.props;\n`)
|
|||
);
|
||||
}
|
||||
|
||||
// handle createCollection, if any
|
||||
if (createCollection) {
|
||||
const ast = babelParser.parse(createCollection, {
|
||||
sourceType: 'module',
|
||||
});
|
||||
traverse(ast, {
|
||||
enter({ node }) {
|
||||
switch (node.type) {
|
||||
case 'VariableDeclaration': {
|
||||
for (const declaration of node.declarations) {
|
||||
// only select Astro.fetchContent() calls here. this utility filters those out for us.
|
||||
if (!isFetchContent(declaration)) continue;
|
||||
|
||||
// a bit of munging
|
||||
let { id, init } = declaration;
|
||||
if (!id || !init || id.type !== 'Identifier') continue;
|
||||
if (init.type === 'AwaitExpression') {
|
||||
init = init.argument;
|
||||
const shortname = path.relative(compileOptions.astroConfig.projectRoot.pathname, state.filename);
|
||||
warn(compileOptions.logging, shortname, yellow('awaiting Astro.fetchContent() not necessary'));
|
||||
}
|
||||
if (init.type !== 'CallExpression') continue;
|
||||
|
||||
// gather data
|
||||
const namespace = id.name;
|
||||
|
||||
if ((init as any).arguments[0].type !== 'StringLiteral') {
|
||||
throw new Error(`[Astro.fetchContent] Only string literals allowed, ex: \`Astro.fetchContent('./post/*.md')\`\n ${state.filename}`);
|
||||
}
|
||||
const spec = (init as any).arguments[0].value;
|
||||
if (typeof spec !== 'string') break;
|
||||
|
||||
const globResult = fetchContent(spec, { namespace, filename: state.filename });
|
||||
|
||||
let imports = '';
|
||||
for (const importStatement of globResult.imports) {
|
||||
imports += importStatement + '\n';
|
||||
}
|
||||
|
||||
createCollection = imports + createCollection.substring(0, declaration.start || 0) + globResult.code + createCollection.substring(declaration.end || 0);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Astro.fetchContent()
|
||||
for (const [namespace, { spec }] of contentImports.entries()) {
|
||||
const globResult = fetchContent(spec, { namespace, filename: state.filename });
|
||||
for (const importStatement of globResult.imports) {
|
||||
state.importStatements.add(importStatement);
|
||||
}
|
||||
contentCode += globResult.code;
|
||||
}
|
||||
|
||||
script = propsStatement + contentCode + babelGenerator(program).code;
|
||||
script = propsStatement + babelGenerator(program).code;
|
||||
const location = { start: module.start, end: module.end };
|
||||
let transpiledScript = transpileExpressionSafe(script, { state, compileOptions, location });
|
||||
if (transpiledScript === null) throw new Error(`Unable to compile script`);
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
* Codegen utils
|
||||
*/
|
||||
|
||||
import type { VariableDeclarator } from '@babel/types';
|
||||
import type { VariableDeclarator, CallExpression } from '@babel/types';
|
||||
|
||||
/** Is this an import.meta.* built-in? You can pass an optional 2nd param to see if the name matches as well. */
|
||||
export function isImportMetaDeclaration(declaration: VariableDeclarator, metaName?: string): boolean {
|
||||
|
@ -18,22 +18,3 @@ export function isImportMetaDeclaration(declaration: VariableDeclarator, metaNam
|
|||
if (metaName && (init.callee.property.type !== 'Identifier' || init.callee.property.name !== metaName)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Is this an Astro.fetchContent() call? */
|
||||
export function isFetchContent(declaration: VariableDeclarator): boolean {
|
||||
let { init } = declaration;
|
||||
if (!init) return false; // definitely not import.meta
|
||||
// this could be `await import.meta`; if so, evaluate that:
|
||||
if (init.type === 'AwaitExpression') {
|
||||
init = init.argument;
|
||||
}
|
||||
// continue evaluating
|
||||
if (
|
||||
init.type !== 'CallExpression' ||
|
||||
init.callee.type !== 'MemberExpression' ||
|
||||
(init.callee.object as any).name !== 'Astro' ||
|
||||
(init.callee.property as any).name !== 'fetchContent'
|
||||
)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
|
|
@ -114,8 +114,21 @@ export async function compileComponent(source: string, { compileOptions, filenam
|
|||
let moduleJavaScript = `
|
||||
import fetch from 'node-fetch';
|
||||
|
||||
// <script astro></script>
|
||||
${/* Global Astro Namespace (shadowed & extended by the scoped namespace inside of __render()) */''}
|
||||
const Astro = {
|
||||
site: new URL('/', ${JSON.stringify(site)}),
|
||||
async fetchContent(importMetaGlobResult) {
|
||||
const {fetchContent: fetchContentInternal} = await import('astro/dist/internal/fetch-content.js');
|
||||
return fetchContentInternal(importMetaGlobResult, import.meta.url);
|
||||
},
|
||||
};
|
||||
const __Astro = Astro;
|
||||
|
||||
|
||||
// Frontmatter Script
|
||||
${result.imports.join('\n')}
|
||||
${result.script}
|
||||
|
||||
${
|
||||
result.hasCustomElements
|
||||
? `
|
||||
|
@ -131,19 +144,24 @@ const __astro_element_registry = new AstroElementRegistry({
|
|||
// \`__render()\`: Render the contents of the Astro module.
|
||||
import { h, Fragment } from 'astro/dist/internal/h.js';
|
||||
const __astroInternal = Symbol('astro.internal');
|
||||
async function __render(props, ...children) {
|
||||
async function __render($props, ...children) {
|
||||
const Astro = {
|
||||
props,
|
||||
site: new URL('/', ${JSON.stringify(site)}),
|
||||
css: props[__astroInternal]?.css || [],
|
||||
request: props[__astroInternal]?.request || {},
|
||||
isPage: props[__astroInternal]?.isPage || false
|
||||
...__Astro,
|
||||
// props,
|
||||
css: $props[__astroInternal]?.css || [],
|
||||
request: $props[__astroInternal]?.request || {},
|
||||
isPage: $props[__astroInternal]?.isPage || false,
|
||||
};
|
||||
|
||||
${result.script}
|
||||
const $state = typeof __state !== 'undefined' ? __state({props: $props}) : {};
|
||||
console.log('$state', $state);
|
||||
|
||||
return h(Fragment, null, ${result.html});
|
||||
}
|
||||
export default { isAstroComponent: true, __render };
|
||||
export default {
|
||||
isAstroComponent: true,
|
||||
__render
|
||||
};
|
||||
|
||||
${result.createCollection || ''}
|
||||
|
||||
|
@ -181,10 +199,9 @@ export async function __renderPage({request, children, props, css}) {
|
|||
return childBodyResult;
|
||||
};
|
||||
|
||||
${result.exports.join('\n')}
|
||||
|
||||
`;
|
||||
|
||||
console.log(moduleJavaScript);
|
||||
return {
|
||||
result,
|
||||
contents: moduleJavaScript,
|
||||
|
|
22
packages/astro/src/internal/fetch-content.ts
Normal file
22
packages/astro/src/internal/fetch-content.ts
Normal file
|
@ -0,0 +1,22 @@
|
|||
export async function fetchContent(importMetaGlobResult: Record<string, () => Promise<any>>, url: string) {
|
||||
if (typeof importMetaGlobResult === 'string') {
|
||||
throw new Error(`[deprecated] "Astro.fetchContent(str)" is now "await Astro.fetchContent(import[dot]meta[dot]glob(str))"`);
|
||||
}
|
||||
const allImporters = [...Object.entries(importMetaGlobResult)];
|
||||
const allImports = await Promise.all(allImporters.map(([spec, imp]) => {
|
||||
return imp().then(mod => {
|
||||
if (!mod.__content) {
|
||||
return;
|
||||
}
|
||||
const urlSpec = new URL(spec, url).pathname.replace(/[\\/\\\\]/, '/');
|
||||
if (!urlSpec.includes('/pages/')) {
|
||||
return mod.__content;
|
||||
}
|
||||
return {
|
||||
...mod.__content,
|
||||
url: urlSpec.replace(/^.*\/pages\//, '/').replace(/\.md$/, ''),
|
||||
};
|
||||
});
|
||||
}));
|
||||
return allImports.filter(Boolean);
|
||||
}
|
|
@ -2,7 +2,7 @@
|
|||
const { collection } = Astro.props;
|
||||
|
||||
export async function createCollection() {
|
||||
const allPosts = Astro.fetchContent('./post/**/*.md');
|
||||
const allPosts = await Astro.fetchContent(import.meta.glob('./post/**/*.md'));
|
||||
const allAuthors = allPosts.map(p => p.author);
|
||||
const uniqueAuthors = [...new Set(allAuthors)];
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
const { collection } = Astro.props;
|
||||
|
||||
export async function createCollection() {
|
||||
const allPosts = Astro.fetchContent('./post/*.md');
|
||||
const allPosts = await Astro.fetchContent(import.meta.glob('./post/*.md'));
|
||||
|
||||
return {
|
||||
routes: allPosts.map((post, i) => {
|
||||
|
|
|
@ -4,7 +4,7 @@ const { collection } = Astro.props;
|
|||
export async function createCollection() {
|
||||
return {
|
||||
async data() {
|
||||
let data = Astro.fetchContent('./post/**/*.md');
|
||||
let data = await Astro.fetchContent(import.meta.glob('./post/**/*.md'));
|
||||
data.sort((a, b) => new Date(b.date) - new Date(a.date));
|
||||
return data;
|
||||
},
|
||||
|
|
|
@ -4,7 +4,7 @@ const { collection } = Astro.props;
|
|||
export async function createCollection() {
|
||||
return {
|
||||
async data() {
|
||||
let data = Astro.fetchContent('./post/**/*.md');
|
||||
let data = await Astro.fetchContent(import.meta.glob('./post/**/*.md'));
|
||||
data.sort((a, b) => new Date(b.date) - new Date(a.date));
|
||||
return data;
|
||||
}
|
||||
|
|
|
@ -4,7 +4,7 @@ const { collection } = Astro.props;
|
|||
export async function createCollection() {
|
||||
return {
|
||||
async data() {
|
||||
let data = Astro.fetchContent('./post/**/*.md');
|
||||
let data = await Astro.fetchContent(import.meta.glob('./post/**/*.md'));
|
||||
data.sort((a, b) => new Date(b.date) - new Date(a.date));
|
||||
return data;
|
||||
},
|
||||
|
|
|
@ -4,7 +4,7 @@ const { collection } = Astro.props;
|
|||
export async function createCollection() {
|
||||
return {
|
||||
async data() {
|
||||
let data = Astro.fetchContent('./post/*.md');
|
||||
let data = await Astro.fetchContent(import.meta.glob('./post/*.md'));
|
||||
data.sort((a, b) => new Date(b.date) - new Date(a.date));
|
||||
return data;
|
||||
},
|
||||
|
|
|
@ -4,7 +4,7 @@ const { collection } = Astro.props;
|
|||
export function createCollection() {
|
||||
return {
|
||||
async data() {
|
||||
const data = Astro.fetchContent('./post/*.md');
|
||||
const data = await Astro.fetchContent(import.meta.glob('./post/*.md'));
|
||||
return data;
|
||||
},
|
||||
pageSize: 1,
|
||||
|
|
|
@ -4,7 +4,7 @@ const { collection } = Astro.props;
|
|||
export async function createCollection() {
|
||||
return {
|
||||
async data() {
|
||||
const episodes = Astro.fetchContent('./episode/*.md');
|
||||
const episodes = await Astro.fetchContent(import.meta.glob('./episode/*.md'));
|
||||
episodes.sort((a, b) => new Date(b.pubDate) - new Date(a.pubDate));
|
||||
return episodes;
|
||||
},
|
||||
|
|
57
yarn.lock
57
yarn.lock
|
@ -76,7 +76,7 @@
|
|||
dependencies:
|
||||
"@babel/highlight" "^7.12.13"
|
||||
|
||||
"@babel/generator@^7.13.9", "@babel/generator@^7.14.2":
|
||||
"@babel/generator@^7.13.9":
|
||||
version "7.14.3"
|
||||
resolved "https://registry.npmjs.org/@babel/generator/-/generator-7.14.3.tgz"
|
||||
integrity sha512-bn0S6flG/j0xtQdz3hsjJ624h3W0r3llttBMfyHX3YrZ/KtLYr15bjA0FXkgW7FpvrDuTuElXeVjiKlYRpnOFA==
|
||||
|
@ -85,29 +85,6 @@
|
|||
jsesc "^2.5.1"
|
||||
source-map "^0.5.0"
|
||||
|
||||
"@babel/helper-function-name@^7.14.2":
|
||||
version "7.14.2"
|
||||
resolved "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.14.2.tgz"
|
||||
integrity sha512-NYZlkZRydxw+YT56IlhIcS8PAhb+FEUiOzuhFTfqDyPmzAhRge6ua0dQYT/Uh0t/EDHq05/i+e5M2d4XvjgarQ==
|
||||
dependencies:
|
||||
"@babel/helper-get-function-arity" "^7.12.13"
|
||||
"@babel/template" "^7.12.13"
|
||||
"@babel/types" "^7.14.2"
|
||||
|
||||
"@babel/helper-get-function-arity@^7.12.13":
|
||||
version "7.12.13"
|
||||
resolved "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.12.13.tgz"
|
||||
integrity sha512-DjEVzQNz5LICkzN0REdpD5prGoidvbdYk1BVgRUOINaWJP2t6avB27X1guXK1kXNrX0WMfsrm1A/ZBthYuIMQg==
|
||||
dependencies:
|
||||
"@babel/types" "^7.12.13"
|
||||
|
||||
"@babel/helper-split-export-declaration@^7.12.13":
|
||||
version "7.12.13"
|
||||
resolved "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.12.13.tgz"
|
||||
integrity sha512-tCJDltF83htUtXx5NLcaDqRmknv652ZWCHyoTETf1CXYJdPC7nohZohjUgieXhv0hTJdRf2FjDueFehdNucpzg==
|
||||
dependencies:
|
||||
"@babel/types" "^7.12.13"
|
||||
|
||||
"@babel/helper-validator-identifier@^7.14.0":
|
||||
version "7.14.0"
|
||||
resolved "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.0.tgz"
|
||||
|
@ -122,7 +99,7 @@
|
|||
chalk "^2.0.0"
|
||||
js-tokens "^4.0.0"
|
||||
|
||||
"@babel/parser@*", "@babel/parser@^7.12.0", "@babel/parser@^7.12.13", "@babel/parser@^7.13.15", "@babel/parser@^7.13.9", "@babel/parser@^7.14.2":
|
||||
"@babel/parser@*", "@babel/parser@^7.12.0", "@babel/parser@^7.13.15", "@babel/parser@^7.13.9":
|
||||
version "7.14.3"
|
||||
resolved "https://registry.npmjs.org/@babel/parser/-/parser-7.14.3.tgz"
|
||||
integrity sha512-7MpZDIfI7sUC5zWo2+foJ50CSI5lcqDehZ0lVgIhSi4bFEk94fLAKlF3Q0nzSQQ+ca0lm+O6G9ztKVBeu8PMRQ==
|
||||
|
@ -134,30 +111,7 @@
|
|||
dependencies:
|
||||
regenerator-runtime "^0.13.4"
|
||||
|
||||
"@babel/template@^7.12.13":
|
||||
version "7.12.13"
|
||||
resolved "https://registry.npmjs.org/@babel/template/-/template-7.12.13.tgz"
|
||||
integrity sha512-/7xxiGA57xMo/P2GVvdEumr8ONhFOhfgq2ihK3h1e6THqzTAkHbkXgB0xI9yeTfIUoH3+oAeHhqm/I43OTbbjA==
|
||||
dependencies:
|
||||
"@babel/code-frame" "^7.12.13"
|
||||
"@babel/parser" "^7.12.13"
|
||||
"@babel/types" "^7.12.13"
|
||||
|
||||
"@babel/traverse@^7.13.15":
|
||||
version "7.14.2"
|
||||
resolved "https://registry.npmjs.org/@babel/traverse/-/traverse-7.14.2.tgz"
|
||||
integrity sha512-TsdRgvBFHMyHOOzcP9S6QU0QQtjxlRpEYOy3mcCO5RgmC305ki42aSAmfZEMSSYBla2oZ9BMqYlncBaKmD/7iA==
|
||||
dependencies:
|
||||
"@babel/code-frame" "^7.12.13"
|
||||
"@babel/generator" "^7.14.2"
|
||||
"@babel/helper-function-name" "^7.14.2"
|
||||
"@babel/helper-split-export-declaration" "^7.12.13"
|
||||
"@babel/parser" "^7.14.2"
|
||||
"@babel/types" "^7.14.2"
|
||||
debug "^4.1.0"
|
||||
globals "^11.1.0"
|
||||
|
||||
"@babel/types@^7.0.0", "@babel/types@^7.12.0", "@babel/types@^7.12.13", "@babel/types@^7.13.0", "@babel/types@^7.14.0", "@babel/types@^7.14.2", "@babel/types@^7.3.0":
|
||||
"@babel/types@^7.0.0", "@babel/types@^7.12.0", "@babel/types@^7.13.0", "@babel/types@^7.14.0", "@babel/types@^7.14.2", "@babel/types@^7.3.0":
|
||||
version "7.14.2"
|
||||
resolved "https://registry.npmjs.org/@babel/types/-/types-7.14.2.tgz"
|
||||
integrity sha512-SdjAG/3DikRHpUOjxZgnkbR11xUlyDMUFJdvnIgZEE16mqmY0BINMmc4//JMJglEmn6i7sq6p+mGrFWyZ98EEw==
|
||||
|
@ -4546,11 +4500,6 @@ global@^4.3.2:
|
|||
min-document "^2.19.0"
|
||||
process "^0.11.10"
|
||||
|
||||
globals@^11.1.0:
|
||||
version "11.12.0"
|
||||
resolved "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz"
|
||||
integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==
|
||||
|
||||
globals@^12.1.0:
|
||||
version "12.4.0"
|
||||
resolved "https://registry.npmjs.org/globals/-/globals-12.4.0.tgz"
|
||||
|
|
Loading…
Reference in a new issue