无法访问Vue文件的脚本标记中的CSS变量

克里斯·A

问题

我正在尝试从.vue文件访问SCSS文件中定义的变量该项目正在使用vue-cli。

根据Vue的文档

“ Vue CLI项目附带对PostCSS,CSS模块和包括Sass,Less和Stylus在内的预处理器的支持。”

但是,如果我创建了variables.css一个名为的变量文件variable,并尝试将其导入脚本中,variable则找不到该文件。

styles / variables.module.css

$variable: 'foo';

:export {
  variable: $variable
}

查看应用

<script>
import variables from "./styles/variables.module.scss";
export default {
  name: "App",
  methods: {},
  computed: {
    variable() {
      console.log(variables);  // Object {}
      return variables.variable || "not found";
    }
  }
};
</script>

<style module>但是,可以在同一vue文件标签中导入variables.css文件

查看应用

<style module lang="scss">
@import "./styles/variables.module.scss";

:export {
  variable: $variable;
}
</style>

我正在努力实现的目标

<p>Importing within &lt;script&gt;, the variable is {{variable}}</p>
// 'not found', should be "foo"
<p>Importing within &lt;style&gt;, the variable is {{$style.variable}}</p>
// correctly showing "foo"

试过:

  • 添加.module到SCSS文件名(根据vue的docs
  • 使用requireModuleExtension: false(来自相同文档)创建vue.config.js文件

可复制的演示

https://codesandbox.io/s/importing-css-to-js-o9p2b?file=/src/App.vue

tuhin47

您需要将webpack和CSS模块化代码添加到中webpack.config.js

npm install -D vue-loader vue-template-compiler webpack

这是工作演示

注意:您vue-template-compilervue的版本应相同

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章