Can't access CSS variables in script tag of Vue file
问题
访问变量:
我正在尝试从
根据Vue的文档:
"Vue CLI projects comes with support for PostCSS, CSS Modules and pre-processors including Sass, Less and Stylus."
但是,如果我创建一个名为
styles / variables.module.css
1 2 3 4 5 | $variable: 'foo'; :export { variable: $variable } |
App.vue
1 2 3 4 5 6 7 8 9 10 11 | import variables from"./styles/variables.module.scss"; export default { name:"App", methods: {}, computed: { variable() { console.log(variables); // Object {} return variables.variable ||"not found"; } } }; |
将variables.css文件导入同一vue文件的
App.vue
1 2 3 4 5 6 7 | <style module lang="scss"> @import"./styles/variables.module.scss"; :export { variable: $variable; } </style> |
我正在努力实现的目标
1 2 3 4 | <p>Importing within , the variable is {{variable}}</p> // 'not found', should be"foo" <p>Importing within <style>, the variable is {{$style.variable}}</p> // correctly showing"foo" |
试过:
-
将
.module 添加到SCSS文件名(根据vue的文档) -
使用
requireModuleExtension: false 创建vue.config.js文件
(来自相同的文档)
可复制的演示
https://codesandbox.io/s/importing-css-to-js-o9p2b?file=/src/App.vue
您需要在
1 | npm install -D vue-loader vue-template-compiler webpack |
这是正在运行的演示
注意:您的
可以使用
我使用此处描述的以下步骤。
安装
将此内容放入您的
1 2 3 4 | "scripts": { ... "scss2json":"echo "export const SCSS_VARS = "> src/styles/scss-variables.generated.ts && scss-to-json src/styles/variables.module.scss >> src/styles/scss-variables.generated.ts" }, |
并使用
1 2 3 | import {SCSS_VARS} from './styles/scss-variables.generated.ts'; ... console.log(SCSS_VARS["$variable"]); |