Skip to content

Commit

Permalink
fix: Convert to ESM (#2227)
Browse files Browse the repository at this point in the history
BREAKING CHANGE:

- Default export removed. Use `import { marked } from 'marked'` or `const { marked } = require('marked')` instead.
- `/lib/marked.js` removed. Use `/marked.min.js` in script tag instead.
- When using marked in a script tag use `marked.parse(...)` instead of `marked(...)`
  • Loading branch information
benmccann committed Nov 2, 2021
1 parent 911dc9c commit 4afb228
Show file tree
Hide file tree
Showing 48 changed files with 5,891 additions and 3,591 deletions.
6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
all:
@cp lib/marked.js marked.js
@uglifyjs --comments '/\*[^\0]+?Copyright[^\0]+?\*/' -o marked.min.js lib/marked.js
@cp lib/marked.cjs marked.cjs
@uglifyjs --comments '/\*[^\0]+?Copyright[^\0]+?\*/' -o marked.min.js lib/marked.cjs

clean:
@rm marked.js
@rm marked.cjs
@rm marked.min.js

bench:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ $ cat hello.html
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
document.getElementById('content').innerHTML =
marked('# Marked in the browser\n\nRendered by **marked**.');
marked.parse('# Marked in the browser\n\nRendered by **marked**.');
</script>
</body>
</html>
Expand Down
125 changes: 59 additions & 66 deletions bin/marked → bin/marked.js
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@
* Copyright (c) 2011-2013, Christopher Jeffrey (MIT License)
*/

const fs = require('fs'),
path = require('path'),
marked = require('../');
import { promises } from 'fs';
import { marked } from '../lib/marked.esm.js';

const { readFile, writeFile } = promises;

/**
* Man Page
*/

function help() {
const spawn = require('child_process').spawn;
async function help() {
const { spawn } = await import('child_process');

const options = {
cwd: process.cwd(),
Expand All @@ -23,16 +24,18 @@ function help() {
stdio: 'inherit'
};

spawn('man', [path.resolve(__dirname, '../man/marked.1')], options)
.on('error', function() {
fs.readFile(path.resolve(__dirname, '../man/marked.1.txt'), 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});
const { dirname, resolve } = await import('path');
const { fileURLToPath } = await import('url');
const __dirname = dirname(fileURLToPath(import.meta.url));
spawn('man', [resolve(__dirname, '../man/marked.1')], options)
.on('error', async() => {
console.log(await readFile(resolve(__dirname, '../man/marked.1.txt'), 'utf8'));
});
}

function version() {
async function version() {
const { createRequire } = await import('module');
const require = createRequire(import.meta.url);
const pkg = require('../package.json');
console.log(pkg.version);
}
Expand All @@ -41,15 +44,15 @@ function version() {
* Main
*/

function main(argv, callback) {
const files = [],
options = {};
let input,
output,
string,
arg,
tokens,
opt;
async function main(argv) {
const files = [];
const options = {};
let input;
let output;
let string;
let arg;
let tokens;
let opt;

function getarg() {
let arg = argv.shift();
Expand Down Expand Up @@ -82,8 +85,6 @@ function main(argv, callback) {
while (argv.length) {
arg = getarg();
switch (arg) {
case '--test':
return require('../test').main(process.argv.slice());
case '-o':
case '--output':
output = argv.shift();
Expand All @@ -102,10 +103,10 @@ function main(argv, callback) {
break;
case '-h':
case '--help':
return help();
return await help();
case '-v':
case '--version':
return version();
return await version();
default:
if (arg.indexOf('--') === 0) {
opt = camelize(arg.replace(/^--(no-)?/, ''));
Expand All @@ -128,62 +129,57 @@ function main(argv, callback) {
}
}

function getData(callback) {
async function getData() {
if (!input) {
if (files.length <= 2) {
if (string) {
return callback(null, string);
return string;
}
return getStdin(callback);
return await getStdin();
}
input = files.pop();
}
return fs.readFile(input, 'utf8', callback);
return await readFile(input, 'utf8');
}

return getData(function(err, data) {
if (err) return callback(err);
const data = await getData();

data = tokens
? JSON.stringify(marked.lexer(data, options), null, 2)
: marked(data, options);
const html = tokens
? JSON.stringify(marked.lexer(data, options), null, 2)
: marked(data, options);

if (!output) {
process.stdout.write(data + '\n');
return callback();
}
if (output) {
return await writeFile(output, data);
}

return fs.writeFile(output, data, callback);
});
process.stdout.write(html + '\n');
}

/**
* Helpers
*/

function getStdin(callback) {
const stdin = process.stdin;
let buff = '';
function getStdin() {
return new Promise((resolve, reject) => {
const stdin = process.stdin;
let buff = '';

stdin.setEncoding('utf8');
stdin.setEncoding('utf8');

stdin.on('data', function(data) {
buff += data;
});
stdin.on('data', function(data) {
buff += data;
});

stdin.on('error', function(err) {
return callback(err);
});
stdin.on('error', function(err) {
reject(err);
});

stdin.on('end', function() {
return callback(null, buff);
});
stdin.on('end', function() {
resolve(buff);
});

try {
stdin.resume();
} catch (e) {
callback(e);
}
});
}

function camelize(text) {
Expand All @@ -204,12 +200,9 @@ function handleError(err) {
* Expose / Entry Point
*/

if (!module.parent) {
process.title = 'marked';
main(process.argv.slice(), function(err, code) {
if (err) return handleError(err);
return process.exit(code || 0);
});
} else {
module.exports = main;
}
process.title = 'marked';
main(process.argv.slice()).then(code => {
process.exit(code || 0);
}).catch(err => {
handleError(err);
});
2 changes: 1 addition & 1 deletion bower.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"markup",
"html"
],
"main": "lib/marked.js",
"main": "lib/marked.cjs",
"license": "MIT",
"ignore": [
"**/.*",
Expand Down
14 changes: 8 additions & 6 deletions build-docs.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
const { mkdir, rmdir, readdir, stat, readFile, writeFile, copyFile } = require('fs').promises;
const { join, dirname, parse, format } = require('path');
const marked = require('./');
const { highlight, highlightAuto } = require('highlight.js');
const titleize = require('titleize');
import { promises } from 'fs';
import { join, dirname, parse, format } from 'path';
import { parse as marked } from './lib/marked.esm.js';
import { HighlightJS } from 'highlight.js';
import titleize from 'titleize';
const { mkdir, rm, readdir, stat, readFile, writeFile, copyFile } = promises;
const { highlight, highlightAuto } = HighlightJS;
const cwd = process.cwd();
const inputDir = join(cwd, 'docs');
const outputDir = join(cwd, 'public');
Expand All @@ -12,7 +14,7 @@ const getTitle = str => str === 'INDEX' ? '' : titleize(str.replace(/_/g, ' '))

async function init() {
console.log('Cleaning up output directory ' + outputDir);
await rmdir(outputDir, { recursive: true });
await rm(outputDir, { force: true, recursive: true });
await mkdir(outputDir);
await copyFile(join(cwd, 'LICENSE.md'), join(inputDir, 'LICENSE.md'));
const tmpl = await readFile(templateFile, 'utf8');
Expand Down
4 changes: 2 additions & 2 deletions component.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"repo": "markedjs/marked",
"description": "A markdown parser built for speed",
"keywords": ["markdown", "markup", "html"],
"scripts": ["lib/marked.js"],
"main": "lib/marked.js",
"scripts": ["lib/marked.cjs"],
"main": "lib/marked.cjs",
"license": "MIT"
}
10 changes: 6 additions & 4 deletions docs/INDEX.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ $ marked -s "*hello world*"
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
document.getElementById('content').innerHTML =
marked('# Marked in browser\n\nRendered by **marked**.');
marked.parse('# Marked in browser\n\nRendered by **marked**.');
</script>
</body>
</html>
Expand All @@ -65,8 +65,10 @@ $ marked -s "*hello world*"
**Node.js**

```js
const marked = require("marked");
const html = marked('# Marked in Node.js\n\nRendered by **marked**.');
import { marked } from 'marked';
// or const { marked } = require('marked');

const html = marked.parse('# Marked in Node.js\n\nRendered by **marked**.');
```


Expand All @@ -79,7 +81,7 @@ We actively support the features of the following [Markdown flavors](https://git
| Flavor | Version | Status |
| :--------------------------------------------------------- | :------ | :----------------------------------------------------------------- |
| The original markdown.pl | -- | |
| [CommonMark](http://spec.commonmark.org/0.29/) | 0.29 | [Work in progress](https://github.com/markedjs/marked/issues/1202) |
| [CommonMark](http://spec.commonmark.org/0.30/) | 0.30 | [Work in progress](https://github.com/markedjs/marked/issues/1202) |
| [GitHub Flavored Markdown](https://github.github.com/gfm/) | 0.29 | [Work in progress](https://github.com/markedjs/marked/issues/1202) |

By supporting the above Markdown flavors, it's possible that Marked can help you use other flavors as well; however, these are not actively supported by the community.
Expand Down
23 changes: 12 additions & 11 deletions docs/USING_ADVANCED.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
## The `marked` function
## The `parse` function

```js
marked(markdownString [,options] [,callback])
import { marked } from 'marked';
marked.parse(markdownString [,options] [,callback])
```

|Argument |Type |Notes |
Expand All @@ -14,7 +15,7 @@ marked(markdownString [,options] [,callback])

```js
// Create reference instance
const marked = require('marked');
import { marked } from 'marked';

// Set options
// `highlight` example uses https://highlightjs.org
Expand All @@ -36,7 +37,7 @@ marked.setOptions({
});

// Compile
console.log(marked(markdownString));
console.log(marked.parse(markdownString));
```

<h2 id="options">Options</h2>
Expand Down Expand Up @@ -67,7 +68,7 @@ console.log(marked(markdownString));
You can parse inline markdown by running markdown through `marked.parseInline`.

```js
const blockHtml = marked('**strong** _em_');
const blockHtml = marked.parse('**strong** _em_');
console.log(blockHtml); // '<p><strong>strong</strong> <em>em</em></p>'

const inlineHtml = marked.parseInline('**strong** _em_');
Expand All @@ -87,7 +88,7 @@ marked.setOptions({
}
});

marked(markdownString, (err, html) => {
marked.parse(markdownString, (err, html) => {
console.log(html);
});
```
Expand All @@ -105,18 +106,18 @@ Marked can be run in a [worker thread](https://nodejs.org/api/worker_threads.htm
```js
// markedWorker.js

const marked = require('marked');
const { parentPort } = require('worker_threads');
import { marked } from 'marked';
import { parentPort } from 'worker_threads';

parentPort.on('message', (markdownString) => {
parentPort.postMessage(marked(markdownString));
parentPort.postMessage(marked.parse(markdownString));
});
```

```js
// index.js

const { Worker } = require('worker_threads');
import { Worker } from 'worker_threads';
const markedWorker = new Worker('./markedWorker.js');

const markedTimeout = setTimeout(() => {
Expand Down Expand Up @@ -144,7 +145,7 @@ importScripts('path/to/marked.min.js');

onmessage = (e) => {
const markdownString = e.data
postMessage(marked(markdownString));
postMessage(marked.parse(markdownString));
};
```

Expand Down
Loading

1 comment on commit 4afb228

@vercel
Copy link

@vercel vercel bot commented on 4afb228 Nov 2, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.