28

我的 Webpack 配置中有以下模块:

module: {
    preLoaders: [
      {
        test: /\.vue$/,
        loader: 'eslint',
        include: projectRoot,
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        loader: 'eslint',
        include: projectRoot,
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      },
      {
        test: /\.js$/,
        loader: 'babel',
        include: projectRoot,
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.html$/,
        loader: 'vue-html'
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass']
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },

您可以看到我正在使用 sass-loader,并且对于 *.scss 文件,我正在定义这个管道:['style', 'css', 'sass'].

然后我有我的 scss 文件:

html {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

(...)

最后,我的 HTML 页面(在 vue.js 的 VUE 文件中)导入了该 scss 文件:

<script>

require('./styles/main.scss')

(...)

</script>

但不知何故,我在启动项目时遇到了这个错误:

ERROR in ./~/css-loader!./~/sass-loader!./~/style-loader!./~/css-loader!./~/sass-loader!./src/styles/main.scss
Module build failed:
html {
^
      Invalid CSS after "...load the styles": expected 1 selector or at-rule, was "var content = requi"
      in /Users/td/uprank/src/styles/main.scss (line 1, column 1)
 @ ./src/styles/main.scss 4:14-247 13:2-17:4 14:20-253

为什么管道会出错?(看起来 webpack 正在尝试处理['css', 'sass', 'style', 'css', 'sass']而不是['style', 'css', 'sass']像在模块中配置的那样。

我究竟做错了什么?

谢谢!

编辑:链接到完整的示例项目:https ://dl.dropboxusercontent.com/u/1066659/dummy.zip

4

1 回答 1

36

发生这种情况的原因是,Vue 自动为 CSS、SASS/SCSS、Stylus 生成加载器配置。

(见projectRoot/build/utils.js~10 到 ~50 行)

所以你看到错误是因为你有一个 webpack 加载器正在尝试导入文件,然后 Vue 正在尝试导入(已经加载的)文件。所以你可以把你的装载机链想象成sass -> css -> style -> sass -> css -> vue-style

为了解决这个问题,您必须摆脱您添加的加载程序:

{
  test: /\.scss$/,
  loaders: ['style', 'css', 'sass']
},

并且只依赖提供的加载器。

您可以通过以下两种方式之一加载样式表:

注意:您必须使用scss而不是sass,因为sass将尝试使用缩进语法而不是括号语法来解析您的样式表。

1:

<style lang="scss">
  @import './styles/main.scss
</style>

2:

<style src="./styles/main.scss"></style>

这两个都将导入样式表,后者只是阻止您向组件添加任何其他样式。

于 2016-05-05T03:44:52.523 回答