使用 Preact CLI 是否可以设置应用程序将在根目录之外托管的路径?
1 回答
你有几个问题需要解决:
1.让Webpack在你的html中输出正确的路径
这是通过在你的根文件夹中创建一个 preact.config.js 来完成的,并将以下内容放在那里
export default (config) => {
config.output.publicPath = '/relativepath/';
};
2. 在您的应用程序中设置您的导航和资产链接
在我看来,解决它的最好方法是使用一个全局变量,你可以在你的应用程序中使用它。因此,再次将 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) 服务器端路由
确保您对 relativepath 的所有请求(包括例如 relativepath/mything/9)将被重写到您的应用程序的 relativepath/index.html(在使用 Apache 的情况下)。然后你的 Javascript 可以处理路由,例如 preact-router
b) 客户端路由(推荐)
启用重新加载 URL 的更简单的选项是使用哈希 URL,从而避免在加载 URL 时通过服务器。
您的 URL 将类似于 www.myserver.com/relativepath/#/mything/9 服务器忽略 # 之后的部分并且仅加载(希望)/relativepath/index.html
您可以使用例如带有哈希历史的 preact-router 来避免服务器端路由,请在此处阅读https://github.com/developit/preact-router#custom-history