【问题标题】:Make variable accessible in all pug files使所有 pug 文件中的变量都可以访问
【发布时间】:2016-08-16 17:21:25
【问题描述】:

使用pug-loader 如何让所有 pug/jade 文件都可以访问一些变量。例如在快递应用中我可以这样做:

app.locals.assetPath = path.resolve('public/assets');

并且变量assetPath 将在所有jade 文件中可用。但是对于 webpack,我无法做到这一点。

在我的webpack.config.js 中,我尝试关注但无法获得工作:

{
  test: /.pug$/,
  loader: 'pug',
  query: {
    root: path.join(__dirname, 'src/app'),

    /*globals: {assetPath: '/hard/coded/value'}*/ //WILL NOT WORK

    /*locals: {assetPath: '/hard/coded/value'}*/ //WILL NOT WORK

    /*locals: {assetPath: '/hard/coded/value'}, globals: ['assetPath']*/ //WILL NOT WORK
  }

【问题讨论】:

  • 如果我正确阅读了源代码,您需要扩展 pug-loader 以支持您想要的内容。你可以在 repo 上打开一个 issue,看看他们怎么说。
  • 打开了一个github问题here

标签: webpack pug


【解决方案1】:

根据我的经验,您有两种选择:

  • 改用pug-html-loader
  • 如果您使用HtmlWebpackPlugin 插件,请将自定义属性添加到其配置中。可以通过所有 pug 模板访问它们。

请查看关于第二个和第一个选项的详细answer

这里也是第二个选项的配置示例:

pug 规则:

{
  test: /\.pug$/,
  loader: 'pug-loader',
  options: {
    // Use `self` namespace to hold the locals
    // Not really necessary
    self: true,
  },
}

HtmlWebpackPlugin 选项:

{
  filename: 'index.html',
  template: 'src/html/index.pug',
  // Your custom variables:
  production: (process.env.NODE_ENV === 'production')
}

index.pug模板:

- const production = self.htmlWebpackPlugin.options.production

if production
  link( rel="stylesheet", type="text/css", href="style.css" )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-20
    • 2020-07-11
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    相关资源
    最近更新 更多