问题
Next js recently added public folder functionality which in its essence resolves urls like these:
background-image: url(/images/test.png);
<img src="/images/test.png" />;
require("/images/test.png")
From wherever you are in your source code to a public
directory located at the root of your project.
I am trying to replicate this in a non next js project that uses webpack, I initially played with publicPath
property, but I'm either missing something or this is not how its done. Hence the question: Given project structure like this how could I resolve those examples mentioned above to my public
folder no matter where I am in the project in prod / dev
?
example project structure
public/
images/
test.png
src/
components/
pages/
webpack.config.js
回答1:
I've got a little bit tricky solution for this.
Add this configuration to your webpack:
resolve: {
alias: {
'/images': path.resolve(__dirname, 'public/images')
}
},
This is tricky solution because webpack will not recognize only '/' alias and you need to set as many aliases as many folders in public folder you have. Example:
resolve: {
alias: {
'/images': path.resolve(__dirname, 'public/images'),
'/audio': path.resolve(__dirname, 'public/audio'),
'/video': path.resolve(__dirname, 'public/video'),
'/etc': path.resolve(__dirname, 'public/etc'),
}
},
Note: you want to require it, so public folder is not a public (or static, assets it can be called when using ssr) folder now. It will be included to the bundle.
来源:https://stackoverflow.com/questions/59016131/how-to-replicate-next-js-public-folder-behaviour-with-webpack