express加载静态文件方案

 

 6月26日

 前几天我加上了,但其实理解,并不深刻。因为因为要加上static路径,就懵了。

// 静态文件服务
app.use('/static', express.static(path.join(__dirname, 'dist')));
app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

这里的含义是:

1,源代码在/dist目录

2,用户访问任何路由,都映射到/dist/index.html

3,加载/dist/index.html时,对应的资源文件是/static/umi.js(举例)

4,'static'路由,把/static/umi.js映射到/dist/umi.js

 

实现的前提是build的时候,要把路径设置为static

配置文件/config/config.ts

export default defineConfig({
  publicPath: process.env.NODE_ENV === 'production' ? '/static/' : '/',
  ...
})

当npm run build的时候,env环境就是production,于是就起作用了。

 

 另外,对于本地开发,其实是没有影响的。除了图片URL。

 

 

 6月19日,经过很多次模式,这个方案终于OK了。

app.use(express.static(path.join(__dirname, 'dist')))


app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});

 

posted @ 2024-06-19 22:50  走走停停走走  Views(1)  Comments(0Edit  收藏  举报