Handlebars Loader与Webpack 4配合使用

7

我一直在寻找如何将handlebars-loader与webpack结合使用的示例,但似乎没有适用于webpack 4的实例。

错误信息

ERROR in ./src/templates/property-list-item.hbs Module build failed: TypeError: Cannot read property 'handlebarsLoader' of undefined at getLoaderConfig (/Users/Sam/Desktop/mettamware/Public/js/node_modules/handlebars-loader/index.js:24:37) at Object.module.exports (/Users/Sam/Desktop/mettamware/Public/js/node_modules/handlebars-loader/index.js:32:15) @ ./src/property-list.js 5:0-58 40:23-31 @ ./src/app.js


当我查看node_modeules/handlerbars-loader/index.js时,问题函数如下

function getLoaderConfig(loaderContext) {
  var query = loaderUtils.getOptions(loaderContext) || {};
  var configKey = query.config || 'handlebarsLoader';
  var config = loaderContext.options[configKey] || {};
  delete query.config;
  return assign({}, config, query);
}

我的webpack.config.js文件

const path = require('path');

module.exports = {
  entry: './src/app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.hbs$/,
        use: [{
          loader: "handlebars-loader",
          options: {
            helperDirs: path.resolve(__dirname, "./src/helpers")
          }
        }]
      }
    ]
  },
  node: {
    fs: 'empty'
  }
};

如果有人能帮忙的话,我将非常感激。我已经搜索了数小时的解决方案,并尝试了很多方法,但没有任何进展。


我曾经认为webpack 4最引人注目的新特性是它是零配置的? - connexo
如果我的回答解决了你的问题,你可以选择勾选标记它为问题的答案吗?谢谢。 - Clay
@Clay 谢谢你的帮助!实际上,在看到你的回答之前,我已经找到了解决方案,但直到现在才有时间发布我的答案。希望我们的答案对其他人有所帮助 :) - Redtama
2个回答

2

同时正在升级旧的webpack 4...

显然,以前可以在配置文件上设置自定义属性。这就是它寻找handlebarsLoader的地方。

如果你在其上设置了handleBarLoader属性,它会发出此错误。

对于加载器选项:webpack 2不再允许在配置中使用自定义属性。

加载器应该更新以通过module.rules中的loader选项传递选项。

在加载器更新之前,可以使用LoaderOptionsPlugin将这些选项传递给加载器:

     plugins: [
       new webpack.LoaderOptionsPlugin({
         // test: /\.xxx$/, // may apply this only for some modules
         options: {
           handlebarsLoader: ...
         }
       })
     ]

在我的情况下,现在将其设置为如下内容:
     plugins: [
       new webpack.LoaderOptionsPlugin({
         options: {
           handlebarsLoader: {}
         }
       })
     ]

2
在Webpack 4中,loaderContext.options已被替换为loaderContext.rootConfig这个提交已经在handlebars-loader包中进行了,以使其与Webpack 4兼容,但尚未发布。
暂时我已卸载了handlebars-loader并使用此分支
以下步骤解决了我的问题: 运行以下两个命令
npm uninstall handlebars-loader
npm install @icetee/handlebars-loader webpack.config.js中,替换为
loader: "handlebars-loader"

with

loader: "@icetee/handlebars-loader"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接