【发布时间】:2021-01-15 03:55:26
【问题描述】:
所以我尝试在 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 文件,然后我必须将其包含在内,但似乎没有人谈论你是如何做到这一点的,并且我在我已经工作的 node/express 应用程序中找不到它,所以也许它并不总是这样做?
当 vue 加载器在 vue SFC 中遇到样式部分时,它实际上对这些样式做了什么?它是否以某种方式通过 javascript 将它们注入页面本身?
哦,我正在使用这个命令来运行构建:
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 或者介于两者之间的某个地方弄错了!这很令人沮丧,因为我在另一个网站上工作,而且我认为这次我没有做任何不同的事情......
【问题讨论】:
-
试试这个
* >>> .foobar {color: red;} -
啊,是的,很深的东西。我试过了,它没有用。对不起,我应该提到它......
-
你安装
vue-template-compiler了吗?见vue-loader.vuejs.org/guide/#manual-setup -
是的,我有这个.... 将我的 package.json 添加到问题中。
-
OP - 你解决过这个问题吗?
标签: javascript vue.js webpack