在 Astro 中将代码捆绑为单独的 js 文件(astro.build、astrojs)

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

我想知道是否有办法让

src/somescript.ts
参与捆绑,但在构建中作为单独的文件输出
dist/somescript.ts
不被页面引用。

构建浏览器扩展时,我们可以引用一个

content_scripts
文件,该文件将用于加载到当前的
activeTab

"content_scripts": [
    {
      "matches": ["https://*/*"],
      "js": ["content.js"],
      "run_at": "document_end"
    }
  ],

我尝试在

public/content.js
上添加脚本并尝试导入
src/somescript.ts
,但它只是逐字复制它。

有没有办法配置 Astro 来捆绑来自

src/somescript.ts
的单独 js 文件?

vite browser-extension astrojs
1个回答
2
投票

为了实现您的目标,您可以使用 Vite Js API 并创建单独处理扩展文件的自定义 Node 脚本。它应该在默认构建脚本完成其工作后执行。

让我们将 Vite JS API 添加到我们的开发依赖项中:

package.json

  "devDependencies": {
    .
    "vite": "4.3.0"
  },

然后创建利用 Vite 构建的自定义脚本:

/* 
    build.mjs
    Custom Vite build script for extension files,
    to execute after default build finishes its work.
*/
import { build } from 'vite';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const extScripts = [
    {
        entry: path.resolve(__dirname, 'src-browser-ext/client-script.ts'),
        fileName: 'client-script'
    },
    /*
        If later you decide to add a background service worker.
    */
    // {
    //  entry: path.resolve(__dirname, 'src-browser-ext/background-sw.ts'),
    //  fileName: 'background-sw'
    // }
];

extScripts.forEach(async (scr) => {
    await build({
        build: {
            // Weather to add sourcemap or not
            // make it false if not required
            sourcemap: 'inline',
            outDir: './dist',
            lib: {
                ...scr,
                formats: ['es']
            },
            emptyOutDir: false
        },
        configFile: false
    });
});

如您所见,我会将扩展脚本保存在单独的源文件夹中:

src-browser-ext

现在我们需要将其集成到我们的构建过程中,在项目的

package.json
中为 scripts 属性添加一个新条目。

    "scripts": {
        .
        .
        "build-ext": "astro build && node build.mjs"
    },

就是这样。现在代替

npm run build
(或
pnpm run build
,无论如何)做
npm run build-ext

但是之后您很有可能会遇到其他问题,例如 Astro 注入的内联脚本在扩展执行时导致安全错误。 我一直在尝试使用 SvelteKit,也像 Astro 一样使用 Vite,在其最新更改之后,除非他们实现了新选项(已在队列中一段时间),否则无法将其用于扩展开发。

据我所知Astro在某些情况下也有同样的问题。 请参阅文档。他们提供的解决方案(为

unsafe-inline
更新 CSP)对于浏览器扩展来说并不好,至少目前是这样。

我还想指出当人们想要使用像 Astro(或 SvelteKit)这样的框架时需要更改的另一个设置,这些框架倾向于在名称以下划线

_
开头的文件夹中输出最终工件。扩展程序无法访问名称以下划线开头的文件夹。在Astro中需要更改的设置是
build.assets
,在下面的示例中我将其更改为
myapp
,默认为
_astro

astro.config.mjs

export default defineConfig({
  build : {
    assets: 'myapp'
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.