I was trying to insert a ImportDeclaration into a snippets of JavaScript code with Babel.js:
const babel = require('babel-core') const t = babel.types const traverse = babel.traverse const template = babel.template const generate = require('babel-generator').default const babylon = require('babylon') const code = [ "import A from 'a'", "import B from 'b'", "export default {", " components: {", " },", " methods: {", " init () {", " }", " }", "}" ].join("\\n") console.log(code) const ast = babylon.parse(code, { sourceType: 'module' }) var n = [] traverse(ast, { ImportDeclaration: { exit(path) { n.push(path) } } }) const name = 'UserDialog', src = './user-dialog.vue' if (n.length) { const importCode = "import " + name + " from '" + src + "'" console.log(importCode) const importAst = template(importCode, { sourceType: 'module' })() // append to last import statement n[n.length - 1].insertAfter(importAst); console.log(generate(ast).code) }
But I got the following error
What's the proper way to do this?
FYI: You can get above code from git clone https://github.com/aztack/babel-test.git
You'd be best off writing this as a Babel plugin, eg
const babel = require('babel-core');
const code = [
"import A from 'a'",
"import B from 'b'",
"export default {",
" components: {",
" },",
" methods: {",
" init () {",
" }",
" }",
"}"
].join("\n");
const result = babel.transform(code, {
plugins: [myImportInjector]
});
console.log(result.code);
function myImportInjector({ types, template }) {
const myImport = template(`import UserDialog from "./user-dialog";`, {sourceType: "module"});
return {
visitor: {
Program(path, state) {
const lastImport = path.get("body").filter(p => p.isImportDeclaration()).pop();
if (lastImport) lastImport.insertAfter(myImport());
},
},
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.