gpt4 book ai didi

preact - 为 Preact CLI 设置基本 URL

转载 作者:行者123 更新时间:2023-12-01 13:31:37 25 4
gpt4 key购买 nike

使用 Preact CLI 是否可以设置应用程序将在根目录之外托管的路径?

例如在 http://mywebsite.com/relativepath/index.html 托管应用程序

最佳答案

您有几个问题需要解决:

1.让Webpack在你的html中输出正确的路径

这是通过在你的根文件夹中创建一个 preact.config.js 来完成的,并将以下内容放在那里

export default (config) => {
config.output.publicPath = '/relativepath/';
};

2. 在您的应用中设置导航和 Assets 链接

在我看来,解决它的最佳方法是使用一个可以在您的应用程序中使用的全局变量。因此,再次将 preact.config.js 编辑为以下内容:
  export default (config, env, helpers) => {
config.output.publicPath = '/relativepath/';

// use the public path in your app as 'process.env.PUBLIC_PATH'
config.plugins.push(
new helpers.webpack.DefinePlugin({
'process.env.PUBLIC_PATH': JSON.stringify(config.output.publicPath || '/')
})
);
};

3.路由

使用您的 preact 应用程序时,导航应该没有问题。但是,如果您尝试加载新的 URL,例如www.myserver.com/relativepath/mything/9,服务器不知道它应该加载位于 www.myserver.com/relativepath/index.html 的单页应用程序

您有两个选择:

a) 服务器端路由

确保您对相对路径(包括例如相对路径/mything/9)的所有请求都将被重写到您的应用程序的相对路径/index.html(在使用 Apache 的情况下)。
然后您的 Javascript 可以处理路由,例如preact-路由器

b) 客户端路由(推荐)

启用重新加载 URL 的更简单选项是使用哈希 url,从而避免在加载 URL 时通过服务器。

您的 URL 将类似于 www.myserver.com/relativepath/#/mything/9
服务器忽略 # 之后的部分,只加载(希望)/relativepath/index.html

您可以使用例如带有哈希历史的 preact-router 可以避免服务器端路由,请在此处阅读 https://github.com/developit/preact-router#custom-history

关于preact - 为 Preact CLI 设置基本 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com