报错出现背景:初始化项目后,执行了
npm i webpack vue vue-loader
vue文件代码:
<template>
<div id='test'>{{ text }}</div>
</template>
<script>
export default {
data() {
return {
text: 'abc'
}
}
}
</script>
<style>
#test {
color: red;
}
</style>
webpack.config.js
const path = require('path')
module.exports = {
entry: path.join(__dirname, 'src/index.js'),
output: {
filename: 'budle.js',
path: path.join(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
]
},
}
入口文件 index.js
import Vue from 'vue'
import App from './app.vue'
const root = document.createElement('div')
document.body.append(root)
new Vue({
render: (h) => h(App)
}).$mount(root)
报错1: npm run build 报了没有找到webpack的错误
原因: webpack和webpack-cil需要同时安装-
报错2:
控制台输出错误
原因: vue-loader 15版本须在配置文件中增加VueLoaderPlugin配置,
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
entry: path.join(__dirname, 'src/index.js'),
output: {
filename: 'budle.js',
path: path.join(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
]
},
plugins: [
new VueLoaderPlugin()
]
}
- 报错3:错误输出
原因:对于css样式编译,需要使用style-loader、css-loader、以及postcss-loader,并且在config.js中声明使用。
const path = require('path')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
entry: path.join(__dirname, 'src/index.js'),
output: {
filename: 'budle.js',
path: path.join(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.css$/,
use: ['style-loader','css-loader']
}
]
},
plugins: [
new VueLoaderPlugin()
]
}
补充:再编译时还需要使用到 vue-template-compiler
package.json配置:
{
"name": "vuestudy",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.config.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"css-loader": "^5.0.1",
"postcss": "^8.2.1",
"postcss-loader": "^4.1.0",
"style-loader": "^2.0.0",
"vue": "^2.6.12",
"vue-loader": "^15.9.5",
"vue-template-compiler": "^2.6.12",
"webpack-cli": "^4.2.0"
},
"devDependencies": {
"webpack": "^5.10.3"
}
}