【问题标题】:Vue webpack build - Failed. You may need an appropriate loader to handle this file typeVue webpack 构建 - 失败。您可能需要适当的加载程序来处理此文件类型
【发布时间】:2019-09-27 15:07:57
【问题描述】:

如果 .vue 文件中有样式,我似乎无法使用单个文件组件构建我的 Vue 项目。

它在没有样式标签的情况下成功构建。但是一添加样式就给我一个错误。

ERROR in ./src/Martins.vue?vue&type=style&index=0&lang=css& (./node_modules/vue-loader/lib??vue-loader-options!./src/Martins.vue?vue&type=style&index=0&lang=css&) 9:0

Module parse failed: Unexpected token (9:0)
You may need an appropriate loader to handle this file type.

> .martins {
|     border: 1px solid black;
|     border-radius: 5px;
 @ ./src/Martins.vue?vue&type=style&index=0&lang=css& 1:0-127 1:143-146 1:148-272 1:148-272
 @ ./src/Martins.vue

这是我的 webpack 配置

const VueLoaderPlugin = require('vue-loader/lib/plugin');

const config = {
  ...
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.css$/,  
        include: /node_modules/,  
        loaders: ['style-loader', 'css-loader'],
      }
    ]
  },
  resolve: {
    extensions: [
      '.js',
      '.vue'
    ]
  },
  plugins: [
    new VueLoaderPlugin()
  ]
}

module.exports = config;

这是我的 webpack 配置

  "dependencies": {
    "css-loader": "^2.1.1",
    "style-loader": "^0.23.1",
    "vue": "^2.6.10"
  },
  "devDependencies": {
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0",
    "vue-loader": "^15.7.0",
    "vue-template-compiler": "^2.6.10",
    "babel-loader": "^8.0.5",
    "@babel/core": "^7.4.0",
    "@babel/preset-env": "^7.4.2"
  }

这是失败的组件

<template>
  <div>
    My name is <span class="martins">Martin</span>
  </div>
</template>

<style lang="css">
    .martins {
        border: 1px solid black;
        border-radius: 5px;
        padding: 4px;
        margin: 4px;
    }
</style>

【问题讨论】:

    标签: javascript vue.js webpack


    【解决方案1】:

    看起来你需要一个不同的 vue 模板样式加载器。

    取自their documentation

    注意:您可能需要安装该依赖项vue-style-loader

    在你的 webpack 配置文件中。

          {
            test: /\.css$/,
            use: [
              'vue-style-loader',
              'css-loader'
            ]
          }
    

    【讨论】:

    • 还是报同样的错误,样式在vue文件本身。
    • 你能更新 webpack 配置或链接到可重现的沙箱吗?
    • 好消息,它成功了!我改变了加载器:['vue-style-loader','css-loader'],使用:['vue-style-loader','css-loader'],
    • 太棒了!您可能还想从 css 部分中排除 node_modules 目录,您目前有 include: /node_modules/,
    猜你喜欢
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 2021-10-25
    • 2019-09-16
    相关资源
    最近更新 更多