onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
669 stars 33 forks source link

How to make Chrome extension with Nextjs 13 #940

Open onmyway133 opened 11 months ago

onmyway133 commented 11 months ago

We can develop Nextjs 13 apps and export it to a Chrome extension.

Start by init the project

npx create-next-app@latest

Here is the project structure with app router and not using src directory. I put an extension to the root of the project, where we can copy over the generated out folder

extension
    - manifest.json
app
    - page.tsx
public
    - images

Here is my script to build and copy over generated out and public images to extension folder

package.json

{
    "name": "my-extension",
    "version": "0.1.0",
    "private": true,
    "scripts": {
        "dev": "next dev",
        "build": "next build",
        "start": "next start",
        "lint": "next lint",
        "copy-out": "mv out/_next out/next && sed -i '' -e 's/\\/_next/\\.\\/next/g' out/**.html && mv out/index.html ./extension && rsync -va --delete-after out/next/ ./extension/next/ && rm -rf out",
        "copy-public": "cp public/images/* extension/images",
        "export": "next build && npm run copy-out && npm run copy-public"
    }
}

We need to specify export mode in next.config.js so we can just next build

/** @type {import('next').NextConfig} */
const nextConfig = {
    output: 'export'
}

module.exports = nextConfig

We should also ignore generated content in extension. Add this to your .gitignore file

# extension
extension/*
!extension/manifest.json
codedbysaify commented 4 months ago

It work till there but when i write JavaScript code in my page.js file it compiled it but when i uploaded that extension to chrome it shows CSP error and is not executing that script which is written in page.js file