diff --git a/index.js b/index.js index 4843b29..c9bf982 100644 --- a/index.js +++ b/index.js @@ -43,7 +43,12 @@ function codeImport(options = {}) { ? parseInt(res.groups.from, 10) : undefined; const toLine = res.groups.to ? parseInt(res.groups.to, 10) : undefined; - const fileAbsPath = path.resolve(file.dirname, filePath); + + if (!options.basePath && !file.dirname) { + throw new Error("Unable to parse base file path. Please configure options.basePath or modify your tooling to include path data, like mdxOptions.filepath.") + } + + const fileAbsPath = path.resolve(options.basePath || file.dirname, filePath); if (options.async) { promises.push( diff --git a/test.js b/test.js index ec1d208..ed0e035 100644 --- a/test.js +++ b/test.js @@ -1,12 +1,24 @@ const codeImport = require('./'); const remark = require('remark'); const path = require('path'); +const os = require('os'); const input = q => ` \`\`\`js file=./__fixtures__/say-#-hi.js${q} \`\`\` `; +const basePathTestPath = path.resolve(process.cwd(), 'gatsby'); +const basePathTestInput = q => ` +\`\`\`js file=../__fixtures__/say-#-hi.js${q} +\`\`\` +`; + +const absolutePathTestInput = q => ` +\`\`\`js file=${path.normalize(process.cwd())}/__fixtures__/say-#-hi.js${q} +\`\`\` +`; + test('Basic file import', () => { expect( remark() @@ -27,6 +39,60 @@ test('Basic file import', () => { `); }); +test('Absolute file import', () => { + expect( + remark() + .use(codeImport, {}) + .processSync({ + contents: absolutePathTestInput(''), + path: path.resolve('test.md'), + }) + .toString() + ).toBe(`\`\`\`js file=${path.normalize(process.cwd())}/__fixtures__/say-#-hi.js +console.log('Hello remark-code-import!');${os.EOL}console.log('This is another line...');${os.EOL}console.log('This is the last line');${os.EOL}console.log('Oops, here is another'); +\`\`\` +`); +}); + +test('Basic file import with basePath', () => { + expect( + remark() + .use(codeImport, { + basePath: basePathTestPath, + }) + .processSync({ + contents: basePathTestInput(''), + path: path.resolve('test.md'), + }) + .toString() + ).toMatchInlineSnapshot(` + "\`\`\`js file=../__fixtures__/say-#-hi.js + console.log('Hello remark-code-import!'); + console.log('This is another line...'); + console.log('This is the last line'); + console.log('Oops, here is another'); + \`\`\` + " + `); +}); + +test('Absolute file import with basePath', () => { + expect( + remark() + .use(codeImport, { + basePath: basePathTestPath, + }) + .processSync({ + contents: absolutePathTestInput(''), + path: path.resolve('test.md'), + }) + .toString() + ).toBe(`\`\`\`js file=${path.normalize(process.cwd())}/__fixtures__/say-#-hi.js +console.log('Hello remark-code-import!');${os.EOL}console.log('This is another line...');${os.EOL}console.log('This is the last line');${os.EOL}console.log('Oops, here is another'); +\`\`\` +`); +}); + test('File import using line numbers', () => { expect( remark()