Webpack 使变量在所有pug文件中都可访问

Webpack 使变量在所有pug文件中都可访问,webpack,pug,Webpack,Pug,使用“如何使所有pug/jade文件都可以访问一些VARABLE”。例如,在express应用程序中,我可以执行以下操作: app.locals.assetPath=path.resolve('public/assets') 变量assetPath将在所有jade文件中可用。但有了webpack,我就无法做到这一点 在我的webpack.config.js中,我尝试了以下内容,但无法获得工作: { test: /.pug$/, loader: 'pug', query: {

使用“如何使所有pug/jade文件都可以访问一些VARABLE”。例如,在express应用程序中,我可以执行以下操作:

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
  }

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

  • 改用,
  • 如果您正在使用
    HtmlWebpackPlugin
    插件,请将自定义属性添加到其配置中。可通过所有pug模板访问它们
请查看有关第二个和第一个选项的详细信息

下面是第二个选项的配置示例:

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" )

如果我阅读的源代码是正确的,那么您需要扩展pug loader来支持您想要的内容。你可以在回购协议上开一个问题,看看他们怎么说