简体   繁体   中英

How to import and use npm packages in background.ts of chrome extension built using angular 10

I am creating a google chrome extension using angular 10. Is it possible to import npm package in background.ts (after transpilation background.js). If yes, then how can we import it and bundle it, so that it can be added in manifest.json file.

I am using @angular-builders/custom-webpack package to convert background.ts to background.js via webpack.

custom.webpack.config.js

const CopyWebPackPlugin = require('copy-webpack-plugin');
const path = require('path');

module.exports = {
    plugins: [
        new CopyWebPackPlugin({
            patterns:[
            {from:'manifest.json', to:''}            
            ]
        }),
      ],    
   entry: { background: 'src/background.ts' }    
}

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "testproject": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./custom.webpack.config.js"
            },
            "outputPath": "dist/testproject",
            "index": "src/index.html",
            "main": "src/main.ts",
            .............
            .............

Manifest.json

{
    "name": "Great Extension",
    "version": "1.0",
    "description": "Build an Extension with Angular",
    "manifest_version": 2,
    "browser_action": {
        "default_popup": "index.html#/home"
    },
    "key": <chrome extension key>,
    "background": {
        "scripts": [
            "./background.js",
            "./runtime.js"          
        ]
    },
    "permissions": [
        "identity"
    ]
}

Note: runtime.js gets created on building angular project using ng build command

I was facing the same issue, I resolved it by adding background.ts in files in tsconfig.app.json

{
  ...
  "files": [
    "src/main.ts",
    "src/polyfills.ts",
    "src/background.ts"
  ],
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM