美文网首页
vue单文件中template使用pug报错问题

vue单文件中template使用pug报错问题

作者: 江Zzz | 来源:发表于2018-11-12 16:37 被阅读0次

今天突然打算在vue单文件组件里面使用pug,按照webpack的逻辑进行了简单的配置:

  module:{
    rules:[
      ...
         {
             test: /\.pug$/,
             loader: "pug-loader"
         }
      ...
    ]
  }

但是结果却是报错:

(Emitted value instead of an instance of Error)
Error compiling template:
var pug = require("!../../node_modules/pug-runtime/index.js");

function template(locals) {var pug_html = "", pug_mixins = {}, pug_interp;pug_html = pug_html + "\u003Ch1\u003E1\u003C\u002Fh1\u003E";;return pug_html;};
module.exports = template;

  • Component template requires a root element, rather than just text
配置loader后webpack报错

经过查证资料应该将pug-loader 替换成pug-plain-loader

  module:{
    rules:[
      ...
         {
             test: /\.pug$/,
             loader: "pug--plain-loader"
         }
      ...
    ]
  }

原因如下:
pug-loader和webpack大多数loader一样,返回的是一个模板函数,而不是我们需要的格式化后的html文本,因此我们不能使用pug-loader,应该使用pug-plain-loader 返回将pug编译后的格式化的html字符串。
修改为pug-plain-loader后问题暂时性解决了,但是假如我们需要在js里面加载.pug文件呢?pug-plain-loader返回的是字符串而不是webpack需要的模块,因此假如是直接加在pug环境的话,需要在pug-plain-loader后用raw-loader来转换成模块代码。配置如下:

// webpack.config.js -> module.rules
{
  test: /\.pug$/,
  oneOf: [
    // this applies to `<template lang="pug">` in Vue components
    {
      resourceQuery: /^\?vue/,
      use: ['pug-plain-loader']
    },
    // this applies to pug imports inside JavaScript
    {
      use: ['raw-loader', 'pug-plain-loader']
    }
  ]
}

参考链接
https://quasar-framework.org/guide/app-pre-processors-and-webpack.html#Pug
https://quasar-framework.org/guide/app-pre-processors-and-webpack.html#Pug

相关文章