跳到主要内容

envPlugin

2023年12月19日
柏拉文
越努力,越幸运

一、认识


envPlugin 可以将 env 替换为 process.env 对象

二、实现


const envPlugin = {
name: 'env',
setup(build) {
build.onResolve({ filter: /^env$/ }, args => ({
path: args.path,
namespace: 'env-ns',
}))

build.onLoad({ filter: /.*/, namespace: 'env-ns' }, () => ({
contents: JSON.stringify(process.env),
loader: 'json',
}))
},
}

三、配置


require('esbuild').build({
entryPoints: ['src/index.jsx'],
bundle: true,
outfile: 'out.js',
// 应用插件
plugins: [envPlugin],
}).catch(() => process.exit(1))

四、效果


使用插件后效果如下:

// 应用了 env 插件后,构建时将会被替换成 process.env 对象
import { PATH } from 'env'

console.log(`PATH is ${PATH}`)