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

* pass static images to webpack-loader

* remove console.log

* fix windows path issue

* fix windows path issue

* add missing deps
This commit is contained in:
Anshul Goyal 2020-08-15 01:03:08 +05:30 committed by GitHub
parent eb4aa19bef
commit 12e9ff6232
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 47 additions and 26 deletions

View file

@ -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",

View file

@ -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

View file

@ -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';
@ -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();
});

View file

@ -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) {
@ -56,6 +76,7 @@ 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
@ -63,25 +84,7 @@ async function processImageNode(node, {filePath, staticDir}) {
// 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}`);
}
}

View file

@ -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';
@ -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) => {

View file

@ -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';