关于vue.js:无法访问Vue文件的脚本标记中的CSS变量

Can't access CSS variables in script tag of Vue file

问题

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

根据Vue的文档:

"Vue CLI projects comes with support for PostCSS, CSS Modules and pre-processors including Sass, Less and Stylus."

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

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文件的<style module>标记中确实可以。

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


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

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

这是正在运行的演示

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


可以使用scss-to-json包导入从.sccs文件生成.tsSCSS变量。 codeandbox演示。

我使用此处描述的以下步骤。

  • 安装npm i --save-dev scss-to-json

  • 将此内容放入您的package.json

  • 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"
     },

    并使用npm run scss2json运行它。 Windows用户将需要调整示例。

  • 访问变量:
  • 1
    2
    3
    import {SCSS_VARS} from './styles/scss-variables.generated.ts';
    ...
    console.log(SCSS_VARS["$variable"]);