編譯官方的Css3.g4檔案為node api
$ antlr4 -no-listener -visitor -Dlanguage=JavaScript css3.g4
編寫index.js檔案呼叫api
import antlr4 from 'antlr4' import MyCssLexer from './CssLexer' import MyCssParser from './CssParser' import MyCssVisitor from './CssVisitor' const chars = new antlr4.InputStream("@import 'xxx.css';") const lexer = new MyCssLexer(chars) const tokens = new antlr4.CommonTokenStream(lexer) const parser = new MyCssParser(tokens) parser.buildParseTrees = true const tree = parser.stylesheet() class Visitor extends MyCssVisitor { visitGoodImport(ctx) { console.log(ctx.String_().getText()) return this.visitChildren(ctx); } } tree.accept(new Visitor())
建立rollup.config.js檔案
import commonjs from 'rollup-plugin-commonjs' import { nodeResolve } from '@rollup/plugin-node-resolve'; import nodePolyfills from 'rollup-plugin-node-polyfills'; export default { input: 'index.js', output: { file: 'bundle.js', format: 'es' }, plugins:[ commonjs(), nodePolyfills(), nodeResolve({ preferBuiltins: false }) ] };
打包,並執行
$ rollup --config rollup.config.js $ node bundle.js
遇到的問題:
- Antlr4打包出來的CssParser.js可能會有一些語法錯誤,我們可以自行修改一下。
贊助我
本作品採用《CC 協議》,轉載必須註明作者和本文連結