How to replicate next js “public” folder behaviour with webpack?

余生颓废 提交于 2021-01-28 01:18:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!