所以我尝试在 vuejs 单文件组件中使用样式。我之前在一个节点应用程序中有过这个工作,但这是一个 python/flask 后端。 (并不是说我认为这应该重要)。 Vue 正确地渲染了组件,一切似乎都很好,但它完全忽略了我的样式标签。
这是我的 test.vue:
<template>
<div>
<span class="foobar">Hello {{ foo }}</span>
</div>
</template>
<script>
let my_component = {
data: function () {
return {
foo: "world"
}},
}
export default my_component
</script>
<style scoped>
.foobar {
color: red;
}
</style>
这是 HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test SFC Page</title>
</head>
<body>
<div id="test_component"></div>
<script src="/static/js/test.js"></script>
</body>
</html>
test.js的内容:
import Vue from 'vue'
import TestComponent from './test.vue'
new Vue({
el: "#test_component",
render: h => h(TestComponent),
})
我的 webpack 配置非常非常简单。我基本上使用了与我的 node/expressjs 站点相同的那个,因为它有效,而 webpack 让我头疼。
const {VueLoaderPlugin} = require('vue-loader');
const config = {
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
},
{
test: /\.js$/,
loader: 'babel-loader',
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader',
],
},
]
},
plugins: [
new VueLoaderPlugin(),
],
}
module.exports = config
但显然我做错了什么。在谷歌搜索之后(并在堆栈溢出上花费了大量时间),似乎暗示 webpack 将为此创建一个单独的 css 文件,然后我必须包含它,但似乎没有人谈论你是如何做到这一点的,并且我在我已经工作的节点/快速应用程序中找不到它,所以也许它并不总是这样做?
当 vue 加载器遇到 vue SFC 中的样式部分时,它实际上如何处理这些样式?它会以某种方式通过 javascript 将它们注入(inject)页面本身吗?
哦,我正在使用这个命令来运行构建:
npx webpack --display-error-details --entry ./static/test/test.js --config ./scripts/webpack.config.js -o ./build/site/static/js/test.js --mode=development
最后一条信息 - 肯定有部分工作正常,因为我的最终 HTML 输出包含 scoped 放入其中的额外数据标记。根据 chrome 的检查员 - 最终的 HTML 看起来像这样:
<div data-v-3d196e1c>
<span data-v-3d196e1c class="foobar">Hello world</span>
</div>
最后是我的 package.json:
"name": "my_app",
"version": "1.0.0",
"description": "Description Goes Here",
"main": "app.js",
"dependencies": {
"axios": "^0.20.0",
"vue": "^2.6.12",
"vue-style-loader": "^4.1.2",
"zxcvbn": "^4.4.2"
},
"devDependencies": {
"@babel/core": "^7.11.6",
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/preset-env": "^7.11.5",
"babel-loader": "^8.1.0",
"cross-env": "^7.0.2",
"css-loader": "^4.3.0",
"html-webpack-plugin": "^4.4.1",
"vue-loader": "^15.9.3",
"vue-template-compiler": "^2.6.12",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+ssh://git@gitlab.com/raphael_disanto/rpg.git"
},
"author": "RDSK",
"license": "ISC",
"bugs": {
"url": "https://gitlab.com/raphael_disanto/rpg/issues"
},
"homepage": "https://gitlab.com/raphael_disanto/rpg#readme"
}
所以我完全迷路了。我不知道我是在使用 webpack、vue 还是介于两者之间的某个地方弄错了!这令人沮丧,因为我在不同的站点上工作,我认为这次我没有做任何不同的事情......
最佳答案
我有这个完全相同的问题,并且正在改变
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader',
],
},
到
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
],
},
修复它。
关于javascript - Vue 单文件组件不显示样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64121278/