pugjs / pug-loader

Pug loader module for Webpack
MIT License
425 stars 119 forks source link

require a variable #116

Closed njleonzhang closed 5 years ago

njleonzhang commented 5 years ago

is there a method which I can require resource from a pug variable?

- var url = './image/xxxx.png'

img(src=require( #{ url } ), width='150px')

error:

  Syntax Error: Unexpected character '#'
njleonzhang commented 5 years ago

After study, I find this is a questions about webpack. When require a dynamic file path, we must indicate the file extension literally. It works in this way:

- var url = './image/xxxx'

img(src=require(url + './png'), width='150px')

refer to: https://stackoverflow.com/questions/39463459/dynamic-file-path-in-require-with-webpack

Serrulien commented 5 years ago

@njleonzhang You found a workaround but what you said is not the cause. The thing that made your require call work is the creation of a context and not the addition of the file extension. Instead of using the #{} syntax, we have to use the attribute interpolation syntax. As i described in https://github.com/pugjs/pug-loader/issues/122#issuecomment-516387317, we can use string casting to pass a variable when calling require so as create a dynamic require context.