Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(v2): pass images in static dir to webpack-loader #3283

Merged
merged 5 commits into from
Aug 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/docusaurus-mdx-loader/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"@babel/parser": "^7.9.4",
"@babel/traverse": "^7.9.0",
"@docusaurus/core": "^2.0.0-alpha.61",
"@docusaurus/utils": "^2.0.0-alpha.61",
"@mdx-js/mdx": "^1.5.8",
"@mdx-js/react": "^1.5.8",
"escape-html": "^1.0.3",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ exports[`transformImage plugin transform md images to <img /> 1`] = `

<img alt={\\"img\\"} src={require(\\"!url-loader?limit=10000&name=assets/images/[name]-[hash].[ext]&fallback=file-loader!./img.png\\").default} />

<img alt={\\"img\\"} src={require(\\"!url-loader?limit=10000&name=assets/images/[name]-[hash].[ext]&fallback=file-loader!./img.png\\").default} title={\\"Title\\"} /> ![img](/img.png)
<img alt={\\"img\\"} src={require(\\"!url-loader?limit=10000&name=assets/images/[name]-[hash].[ext]&fallback=file-loader!./img.png\\").default} title={\\"Title\\"} /> <img alt={\\"img\\"} src={require(\\"!url-loader?limit=10000&name=assets/images/[name]-[hash].[ext]&fallback=file-loader!packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/fixtures/img.png\\").default} />

## Heading

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import {join} from 'path';
import {join, relative} from 'path';
import remark from 'remark';
import mdx from 'remark-mdx';
import vfile from 'to-vfile';
Expand All @@ -24,28 +24,35 @@ const processFixture = async (name, options) => {
return result.toString();
};

// avoid hardcoding absolute
const staticDir = `./${relative(process.cwd(), join(__dirname, 'fixtures'))}`;

describe('transformImage plugin', () => {
test('fail if image does not exist', async () => {
await expect(
processFixture('fail', {staticDir: join(__dirname, 'fixtures')}),
processFixture('fail', {
staticDir,
}),
).rejects.toThrowErrorMatchingSnapshot();
});
test('fail if image url is absent', async () => {
await expect(
processFixture('noUrl', {staticDir: join(__dirname, 'fixtures')}),
processFixture('noUrl', {
staticDir,
}),
).rejects.toThrowErrorMatchingSnapshot();
});

test('transform md images to <img />', async () => {
const result = await processFixture('img', {
staticDir: join(__dirname, 'fixtures'),
staticDir,
});
expect(result).toMatchSnapshot();
});

test('pathname protocol', async () => {
const result = await processFixture('pathname', {
staticDir: join(__dirname, 'fixtures'),
staticDir,
});
expect(result).toMatchSnapshot();
});
Expand Down
41 changes: 22 additions & 19 deletions packages/docusaurus-mdx-loader/src/remark/transformImage/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,31 @@ const path = require('path');
const url = require('url');
const fs = require('fs-extra');
const {getFileLoaderUtils} = require('@docusaurus/core/lib/webpack/utils');
const {posixPath} = require('@docusaurus/utils');

const {
loaders: {inlineMarkdownImageFileLoader},
} = getFileLoaderUtils();

const createJSX = (node, pathUrl) => {
node.type = 'jsx';
node.value = `<img ${node.alt ? `alt={"${node.alt}"}` : ''} ${
node.url
? `src={require("${inlineMarkdownImageFileLoader}${pathUrl}").default}`
: ''
} ${node.title ? `title={"${node.title}"}` : ''} />`;

if (node.url) {
delete node.url;
}
if (node.alt) {
delete node.alt;
}
if (node.title) {
delete node.title;
}
};

// Needed to throw errors with computer-agnostic path messages
// Absolute paths are too dependant of user FS
function toRelativePath(filePath) {
Expand Down Expand Up @@ -56,32 +76,15 @@ async function processImageNode(node, {filePath, staticDir}) {
// absolute paths are expected to exist in the static folder
const expectedImagePath = path.join(staticDir, node.url);
await ensureImageFileExist(expectedImagePath, filePath);
createJSX(node, posixPath(expectedImagePath));
}
// We try to convert image urls without protocol to images with require calls
// going through webpack ensures that image assets exist at build time
else {
// relative paths are resolved against the source file's folder
const expectedImagePath = path.join(path.dirname(filePath), node.url);
await ensureImageFileExist(expectedImagePath, filePath);

node.type = 'jsx';
node.value = `<img ${node.alt ? `alt={"${node.alt}"}` : ''} ${
node.url
? `src={require("${inlineMarkdownImageFileLoader}${
node.url.startsWith('./') ? node.url : `./${node.url}`
}").default}`
: ''
} ${node.title ? `title={"${node.title}"}` : ''} />`;

if (node.url) {
delete node.url;
}
if (node.alt) {
delete node.alt;
}
if (node.title) {
delete node.title;
}
createJSX(node, node.url.startsWith('./') ? node.url : `./${node.url}`);
}
}

Expand Down
6 changes: 5 additions & 1 deletion packages/docusaurus-plugin-content-pages/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ import {Configuration, Loader} from 'webpack';
import admonitions from 'remark-admonitions';
import {PluginOptionSchema} from './pluginOptionSchema';
import {ValidationError} from '@hapi/joi';
import {DEFAULT_PLUGIN_ID} from '@docusaurus/core/lib/constants';
import {
DEFAULT_PLUGIN_ID,
STATIC_DIR_NAME,
} from '@docusaurus/core/lib/constants';

import {PluginOptions, LoadedContent, Metadata} from './types';

Expand Down Expand Up @@ -178,6 +181,7 @@ export default function pluginContentPages(
options: {
remarkPlugins,
rehypePlugins,
staticDir: path.join(siteDir, STATIC_DIR_NAME),
// Note that metadataPath must be the same/in-sync as
// the path from createData for each MDX.
metadataPath: (mdxPath: string) => {
Expand Down
6 changes: 6 additions & 0 deletions website/src/pages/examples/markdownPageExample.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,14 @@ function Button() {
}
```

### Using relative path

![](../../../static/img/docusaurus.png)

### Using absolute path

![](/img/docusaurus.png)

import Tabs from '@theme/Tabs';

import TabItem from '@theme/TabItem';
Expand Down