const acorn = require("acorn");
const code = `export default "hello, world";`;
const parsed = acorn.parse(code, {
sourceType: "module",
});
const stringLiteral = parsed.body[0].declaration.arguments[0].value;
// 输出:hello, world
console.log(stringLiteral);
const esprima = require('esprima');
const code = 'var hello = "hello, world";';
const parsed = esprima.parseScript(code);
const stringLiteral = parsed.body[0].declarations[0].init.value;
// 输出:hello, world
console.log(stringLiteral);
var acorn = require("acorn");
// 解析字符串并遍历 AST
var code = "'hello world'";
var ast = acorn.parse(code);
var strings = [];
acorn.walk.simple(ast, {
Literal(node) {
if (typeof node.value === "string") {
strings.push(node.value);
}
}
});
console.log(strings[0]); // 输出: hello world
var esprima = require("esprima");
// 解析字符串并遍历 AST
var code = "'hello world'";
var ast = esprima.parseScript(code);
var strings = [];
esprima.visit(ast, {
Literal(node) {
if (typeof node.value === "string") {
strings.push(node.value);
}
}
});
console.log(strings[0]); // 输出: hello world