`bun build` 捆绑时用实际值替换对环境变量的引用

问题描述 投票:0回答:1

有没有办法让

bun build
将环境变量的引用替换为其实际的原始值:

console.log(Bun.env.API_KEY) // this get printed

// make a global variable for the API key
const API_KEY = Bun.env.API_KEY

const result = await Bun.build({
  entrypoints: ['./src/background.js', './src/content.js'], // specify the entrypoints of your extension
  outdir: './dist', // specify the output directory for the bundled files
  target: 'browser', // specify the target environment for the bundle
  format: 'esm', // specify the module format for the bundle
  external: ['chrome'], // specify any external imports that should not be bundled
})

if (!result.success) {
  console.error('Build failed')
  for (const message of result.logs) {
    // Bun will pretty print the message object
    console.error(message)
  }
}

dist中的输出如下所示:

dist/content.js

// src/content.js var selectedText = window.getSelection().toString().trim().replace(/\s+/g, " "); if (selectedText) { const url = `https://www.google.com/maps/embed/v1/search?q=${encodeURIComponent(selectedText)}&key=${Bun.env.API_KEY}`; // Want the string instead of the ref ...
    
javascript bundle bun
1个回答
0
投票
这可行,但我想找到一种更干净的方法。

const { exec } = require('child_process') const result = await Bun.build({ entrypoints: ['./src/background.js', './src/content.js', 'manifest.json', 'images/icon16.png'], outdir: './dist', target: 'browser', format: 'esm', external: ['chrome'], // specify any external imports that should not be bundled }) if (result.success) { console.log('Build succeeded') exec(`sed -i '' 's/Bun.env.API_KEY/"${Bun.env.API_KEY}"/g' ./dist/src/content.js`) } if (!result.success) { console.error('Build failed') for (const message of result.logs) { // Bun will pretty print the message object console.error(message) } }
    
© www.soinside.com 2019 - 2024. All rights reserved.