I am trying to learn to write a loader in vue2 project. And I want to use this loader to add some attributes in some tag automatically before processing to vue-loader.
The code of my loader is:
module.exports = function (content) {
const templateMatch = content.match(/<template>([\s\S]*?)<\/template>/);
let restContent = content
if (templateMatch) {
const templateContent = templateMatch[1];
restContent = content.replace(/<template>[\s\S]*?<\/template>/, '');
let returnContent = templateContent.replace(/<\/el-/g, '\n</el-')
returnContent = returnContent.replace(/<el-/g, '\n<el-')
returnContent = returnContent.replace(/<input/g, '\n<input')
var regInput = /<(input)([^<>]*)>/g // tmp
let contentArr = returnContent.split('\n')
let resultArr = contentArr.map((item, index) => {
if (regInput.test(item)) {
item = item.replace(/<input/g, '<input name="input_name"')
}
return item
})
const result = resultArr.join('\n')
console.log('result', result)
return `module.exports = ${JSON.stringify(result + restContent)};`
} else {
return `module.exports = ${JSON.stringify(content)};`
}
}
And I use it in vue.config.js:
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack: config => {
config.module
.rule('vue')
.test(/\.vue$/)
.use('vue-loader')
.loader('vue-loader')
.end()
.use('my-loader')
.loader(path.resolve(__dirname, './my-loader.js'))
.end()
}
})
After run pnpm serve command, I meet a error that shows:
> 1 | \n#app {\n font-family: Avenir, Helvetica, Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n text-align: center;\n color: #2c3e50;\n margin-top: 60px;\n}\n
|
ERROR in ./src/App.vue?vue&type=script&lang=js
From console log I can see that the attribute has been added into the input tag
result
<div id="app">
<el-input v-model="input" placeholder="please input">
</el-input>
<input name="input_name" v-model="input2" placeholder="please input" />
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
But I have no idea why it parse failed finally.
I have upload the project code to github Thank you for your answer sincerely.