1

前端框架Svelte踩坑记录 - 搞搞震

 3 years ago
source link: https://www.wujingquan.com/posts/932a3d86.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

环境变量的设置

最近用Svelte开发了个小应用,在不同的开发环境使用不同的变量,以达到区分 开发环境生产环境

核心原理是利用 dotenv 模块来加载不同的路径的文件来区分不同的环境变量,用 @rollup/plugin-replace 插件来把代码中的使用 字符串 占位的值来替换 dotenv 加载的变量。

以下代码演示个大概:

//.env.pord

__HOST__ = https://api.example.com
//.env.dev

__HOST__ = http://localhost
// rollup.config.js

const production = !process.env.ROLLUP_WATCH;

export default {
    plugins: [
        // ... 这里省略一堆插件的配置
        !production && config({path: '.env.dev'}) && replace({
			__HOST__: process.env.__HOST__
		}),
		production && config({path: '.env.prod'}) && replace({
			__HOST__: process.env.__HOST__
		}),
    ]
}

下面 console.log(HOST) 会根据不同环境来输出不同的值,在 生产环境 输出的是 https://api.example.com ,在 开发环境 输出的则是 http://localhost

// App.svelte

const HOST = '__HOST__'
console.log(HOST)

参考:https://medium.com/dev-cafe/how-to-setup-env-variables-to-your-svelte-js-app-c1579430f032

部署到子目录

修改 public 下的 index.html 文件内容,把引用的资源从 绝对路径 修改为 相对路径


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK