Add webpack and TypeScript to a Chrome extension (2024)

Victor on Software
23 May 202427:50

Summary

TLDRВ этом видео вторая часть серии о создании готового к выпуску расширения для Chrome. Автор рассказывает о добавлении инструмента сборки Webpack и TypeScript в проект, созданный в предыдущем видео. Объясняется, как установить и настроить Webpack для объединения и минификации файлов, а также как настроить TypeScript для улучшения качества кода и ранней обнаружения ошибок. Видео также демонстрирует, как использовать конфигурационные файлы Webpack и TypeScript, и как перевести существующий код на TypeScript. В заключении рассматривается отладка расширения и использование типов Chrome для более эффективной разработки.

Takeaways

  • 😀 В серии видео рассматривается создание готового к выпуску расширения для Chrome.
  • 🛠️ В данном видео добавляются Webpack и TypeScript в проект, созданный в предыдущем видео.
  • 💻 Необходимо наличие Node.js и npm для работы с webpack и другими инструментами.
  • 📄 Создается файл package.json для хранения информации о проекте и зависимостях.
  • 🔧 Webpack используется как бандлер для объединения файлов и минимизации кода для производительности.
  • 📝 Создаются конфигурационные файлы Webpack: common.js, webpack.dev.js и webpack.prod.js.
  • 📁 Создается папка static для хранения неизменных файлов расширения, таких как manifest.json.
  • 🔄 Используется webpack --watch для автоматической сборки при внесении изменений.
  • ⚙️ TypeScript добавляет статическую типизацию и другие функции в JavaScript, улучшая качество кода.
  • 🔧 Для работы с TypeScript необходимы TS Node, TypeScript Loader и типы для Chrome.
  • 🛠️ После конфигурации TypeScript, необходимо обновить webpack.config.js и перевести JavaScript-файлы в TypeScript.

Q & A

  • Что предполагает создание готового к выпуску расширения Chrome?

    -Создание готового к выпуску расширения Chrome включает в себя добавление инструментов сборки, таких как webpack, и использования TypeScript для улучшения качества кода и обеспечения более ранней выявления ошибок.

  • Какие инструменты разработки должны быть установлены перед началом работы с расширением Chrome?

    -Для начала работы необходимо установить Node.js, который является средой выполнения JavaScript, и npm, что является менеджером пакетов для JavaScript. Эти инструменты необходимы для запуска webpack и других инструментов разработки.

  • Чем отличается webpack от других инструментов сборки?

    -Webpack - это бандлер, который объединяет несколько файлов с зависимостями в один файл. Он также выполняет другие функции, такие как сжатие и минификация для улучшения производительности.

  • Как создать файл package.json для проекта расширения Chrome?

    -Файл package.json можно создать, выполнив команду 'npm init' или вручную, создав новый файл с именем package.json и добавив в него необходимую информацию о проекте и зависимостях.

  • Что такое TypeScript и зачем его использовать в проекте?

    -TypeScript - это супернадстройка над JavaScript, которая добавляет статические типы и другие функции. Он рекомендуется для использования в проектах, чтобы улучшить качество кода и рано выявлять ошибки благодаря типизации.

  • Какие команды npm используются для установки webpack и связанных с ним пакетов?

    -Для установки webpack и связанных пакетов используются команды вида 'npm install webpack webpack-cli webpack-merge copy-webpack-plugin'.

  • Как настроить webpack для работы с расширением Chrome?

    -Для настройки webpack на работу с расширением Chrome необходимо создать конфигурационные файлы, такие как 'webpack.common.js', 'webpack.dev.js' и 'webpack.prod.js', которые определяют, как будут обрабатываться разные части расширения.

  • Какие преимущества предлагает использование источников карт (Source Maps) в проекте?

    -Источник карты позволяют сопоставить исходный код с сгенерированным JavaScript файлом, что упрощает отладку кода в браузере и обеспечивает более прямую связь между кодом разработки и кодом, который выполняется в браузере.

  • Какие изменения в проекте потребуются для использования TypeScript?

    -Для использования TypeScript в проекте потребуется установить типы для Chrome, настроить конфигурацию TypeScript в файле 'tsconfig.json', а также перевести существующий JavaScript код в TypeScript, исправив возможные ошибки и добавив типы.

  • Как можно упростить запуск webpack в проекте?

    -Для упрощения запуска webpack можно использовать скрипты в файле package.json, где можно определить команды 'npm run start' для запуска в режиме разработки и 'npm run build' для сборки в режиме продакшена.

Outlines

00:00

🛠 Настройка webpack и начало работы с TypeScript

В этом разделе видео курса рассматривается добавление инструментов сборки webpack и TypeScript в уже созданный ранее проект Chrome расширения. Прежде чем приступить к основной части, проверяется наличие Node.js и npm, необходимых для работы с webpack. Создается файл package.json вручную, а затем устанавливаются пакеты webpack, webpack-cli, webpack-merge, copy-webpack-plugin и другие. Объясняется, что webpack является сборщиком, который объединяет несколько файлов с зависимостями в один файл, а также выполняет сжатие и минификацию для улучшения производительности. Создаются конфигурационные файлы webpack: common.js для общей конфигурации и development.js для конкретной настройки разработки.

05:02

🔧 Установка и настройка webpack для разработки

В этом параграфе описывается процесс установки и настройки webpack для разработки Chrome расширения. Создается файл webpack.dev.js с настройками для режима разработки, включая использование inline-карты исходников для упрощения отладки. Также создается файл webpack.prod.js для продакшн-настройки, который включает в себя различные оптимизации для производственной среды. После настройки, webpack запускается с использованием команды 'watch', которая обеспечивает автоматическое обновление сборки при внесении изменений в исходные файлы. Производится проверка работы расширения в Chrome, удаляется старый экземпляр расширения и загружается новый, сгенерированный webpack.

10:02

💡 Внедрение TypeScript в проект

В этом разделе рассказывается о преимуществах использования TypeScript в проекте Chrome расширения для улучшения качества кода и раннего выявления ошибок. Устанавливаются необходимые пакеты для работы с TypeScript, включая сам TypeScript, TS-node для поддержки TypeScript в Node.js и typescript-loader для webpack. Также устанавливаются типы для Chrome, чтобы иметь доступ к типам API Chrome в TypeScript-проекте. Создается конфигурационный файл tsconfig.json с рекомендуемыми настройками и включением Source Maps для упрощения отладки. Далее переписываются существующие конфигурационные файлы webpack на TypeScript и исправляются возникающие ошибки.

15:03

⚙️ Улучшение конфигурации и добавление скриптов в package.json

В этом параграфе описывается процесс оптимизации и упрощения команд webpack с помощью добавления скриптов в файл package.json. Изменяются скрипты для запуска webpack в режиме разработки и продакшена, исправляются опечатки и проверяется корректность работы сборки. Также обсуждается перенос исходных JavaScript-файлов в TypeScript, включая исправление ошибок, возникающих из-за дублирования функций и обновления импортов. После внесения изменений и исправления ошибок, проверяется успешность сборки и функционирования расширения в браузере.

20:10

🕵️‍♂️ Отладка и дальнейшее развитие расширения

В заключительном разделе видео рассматривается отладка различных частей Chrome расширения с использованием инструментов разработчика в браузере. Показывается, как можно установить точки останова и отлаживать код, используя Source Maps, которые были включены в настройках TypeScript. Также обсуждается необходимость добавления типов Chrome в среду разработки для корректного определения типов API Chrome. Наконец, автор видео подводит итоги и анонсирует, что в следующих частях курса продолжатся добавление новых функций и инструментов разработки в проект Chrome расширения.

Mindmap

Keywords

💡Chrome расширение

Chrome расширение - это приложение, которое расширяет функциональность браузера Google Chrome, добавляя новые инструменты и возможности. В видео рассматривается процесс создания готового к выпуску расширения, включая добавление webpack и TypeScript для улучшения структуры и качества кода.

💡Webpack

Webpack - это инструмент сборки JavaScript-приложений, который объединяет несколько файлов с зависимостями в один файл для упрощения загрузки и выполнения. В контексте видео, webpack используется для создания бандлов из JavaScript-файлов расширения Chrome, а также для минификации и сжатия кода для повышения производительности.

💡TypeScript

TypeScript - это язык программирования, разработанный Microsoft, который является надмножеством JavaScript и добавляет в него статические типы и другие функции. В видео упоминается использование TypeScript для раннего выявления ошибок и повышения качества кода расширения Chrome.

💡npm

npm (Node Package Manager) - это менеджер пакетов для JavaScript, который позволяет устанавливать, обновлять и удалять пакеты, а также управлять зависимостями в проекте. В видео используется для установки webpack, TypeScript и других инструментов, необходимых для разработки расширения.

💡package.json

package.json - это файл конфигурации, используемый в проектах Node.js и других JavaScript-проектах для хранения информации о проекте и списка зависимостей. В видео создается package.json вручную для хранения информации о проекте расширения Chrome.

💡Бандлинг

Бандлинг - это процесс объединения нескольких файлов кода в один файл для оптимизации загрузки и выполнения. В видео webpack используется для бандлинга JavaScript-файлов расширения Chrome в один файл для упрощения процесса загрузки расширения.

💡Конфигурация webpack

Конфигурация webpack - это процесс настройки параметров и опций для webpack, чтобы определить, как должны быть обработаны и объединены файлы проекта. В видео рассматривается создание конфигурационных файлов для webpack, включая общие настройки и настройки для разработки и производства.

💡Статичные ресурсы

Статичные ресурсы - это файлы, не требующие обработки или компиляции, такие как изображения, CSS-файлы и HTML-файлы. В видео упоминается создание папки 'static' для хранения таких файлов расширения Chrome, которые не подлежат изменениям в процессе сборки.

💡Типизация

Типизация - это процесс определения и использования типов данных в коде для улучшения его читаемости, безопасности и упрощения процесса отладки. В видео TypeScript используется для добавления типизации в JavaScript-код расширения Chrome, что позволяет раннее выявление ошибок и повышение качества кода.

💡Инструменты разработки

Инструменты разработки - это программное обеспечение, используемое для написания, тестирования и отладки кода. В видео упоминается использование инструментов, таких как webpack и TypeScript, для создания и оптимизации кода расширения Chrome.

Highlights

Introduction to adding webpack and TypeScript to a Chrome extension project.

Prerequisites check for Node.js and npm installations.

Creating a package.json file manually for project information and dependencies.

Explanation of webpack as a bundler for JavaScript files.

Installation of webpack, webpack CLI, and other development tools.

Creation of webpack.common.js for shared configuration across environments.

Organization of Chrome extension files into 'source' and 'static' directories.

Setting up webpack.dev.js for development configuration with inline source maps.

Conversion of JavaScript webpack configurations to TypeScript.

Installation of TypeScript and related development dependencies.

Configuration of TypeScript using tsconfig.json with source map enabled.

Running webpack in watch mode to automatically rebuild on file changes.

Loading the Chrome extension from the 'dist' directory for testing.

Introduction to TypeScript as a superset of JavaScript with added static typing.

Debugging the Chrome extension in the browser using source maps.

Fixing TypeScript errors and ensuring type safety in the code.

Using npm scripts to simplify webpack build and start commands.

Final testing and debugging of the Chrome extension with TypeScript.

Note on the necessity of configuring the IDE for global types like Chrome.

Transcripts

play00:00

this is the second part of our series on

play00:02

creating a production ready Chrome

play00:04

extension so in this video we will add

play00:07

the webpack build tool and

play00:10

typescript to our project that we

play00:13

created in the previous video so let's

play00:16

uh jump into into some prerequisites so

play00:19

first we need to make sure we have no JS

play00:21

which is a JavaScript runtime

play00:25

installed um we will need it to run

play00:28

webpack and then any future development

play00:30

tools We'll add and we also need npm

play00:33

which is a package manager for

play00:36

JavaScript so for example I can find the

play00:39

web pack pack web pack package here so

play00:42

in order to check whether these are

play00:44

installed we just do um node DV to see

play00:48

which version we have installed npm DV

play00:50

to see which version of npm we have

play00:53

installed okay so let's jump in so we

play00:56

have our code from uh the previous

play01:00

video we got we got our basic Chrome

play01:04

extension with all the files and source

play01:06

and first thing we're going to do is

play01:08

we're going to create a package.json

play01:10

file so it it holds uh basically project

play01:13

information and dependency information

play01:16

we could just run npm init to create

play01:19

that file npm init um but in this case

play01:23

we'll just do it manually so let's

play01:25

create a new file package.json

play01:30

and then we'll put some text in it

play01:34

nothing

play01:36

special okay so let's move on to uh

play01:40

adding

play01:42

webpack so what is webpack well

play01:45

essentially webpack is a bundler it

play01:47

create it takes multiple files with

play01:49

dependency in them and then in them and

play01:51

then creates a single

play01:55

file um so in our

play01:58

case we're going to have multiple

play02:00

JavaScript files that will then be

play02:03

bundled into a single Javascript file

play02:06

now in addition to this bundling it also

play02:08

does some other things like uh

play02:10

compression and minification um for

play02:13

performance

play02:15

reasons so let's uh let's install

play02:20

it so we're going to run these commands

play02:23

we're going to install webpack itself

play02:25

webpack CLI because we're going to be

play02:27

running it from the command line uh web

play02:30

pack merge merge is going to merge our

play02:32

kind of common config and our

play02:34

development config because we're going

play02:35

to have two configurations one for

play02:37

development one for production and then

play02:39

this copy plugin basically just for

play02:42

copying static assets so let's install

play02:44

all these using this

play02:49

command so we can look at what happened

play02:52

in our

play02:53

directory see we now have a new package

play02:56

do- log. jent file which was created by

play02:59

npm right and it holds the exact

play03:03

versions of all these dependencies and

play03:06

their

play03:11

subpena

play03:13

package.json so we see uh the versions

play03:17

that got

play03:19

installed all right let's move on to the

play03:21

configuration so configuring webpack um

play03:25

by default it doesn't really require

play03:27

configuration but because we're using a

play03:29

chrome extension and uh Chrome extension

play03:32

has three parts uh so we effectively is

play03:35

going to have three different

play03:37

bundles um so we need to we need to

play03:40

configure all of that so let's go ahead

play03:42

and create a new file uh we're going to

play03:44

create a file called Web pag.

play03:48

common.js that's where our common

play03:50

configuration is going to

play03:53

be um so we're going to have the

play03:55

background script content script and the

play03:57

popup scripts so these are the three

play03:59

bundles we're going to be creating

play04:02

they're all going to go into this this

play04:04

directory so previously we were loading

play04:06

everything from

play04:07

Source now uh we're going to be loading

play04:10

from

play04:11

this um and

play04:14

then we're going to have a static folder

play04:16

so some of these files we're not going

play04:18

to mess with at this point so we're

play04:20

going to move them to a static directory

play04:22

so let's create a new directory called

play04:24

Static and let's move

play04:27

manifest um manifest Json and these

play04:31

popup CSS popup HTML let's move them

play04:34

into

play04:39

static okay um so we have the common

play04:42

file now we're going to create

play04:45

a um a development config that's going

play04:48

to point to this common config so this

play04:50

common config is going to be consumed by

play04:51

both development and production config

play04:53

so let's create

play04:54

new file webpack dod. JS that's going to

play04:59

be our development

play05:02

config so we're going to put development

play05:04

mode here and we're going to use an

play05:06

inline Source map um inline Source map

play05:09

basically just puts maps are generated

play05:13

uh the generated JavaScript back to our

play05:15

original JavaScript and it all does in

play05:18

the in in the single file so this is

play05:19

often used um during development using

play05:22

an inline Source

play05:24

M um and then we add our uh production

play05:29

config

play05:32

we're going to add a production

play05:36

config this our production config okay

play05:38

so where we are now we've

play05:42

refactored are we ready to run the web

play05:44

pack let's let's try to run

play05:47

it go back to our

play05:51

terminal and um we installed weback so

play05:55

by default it can be run by from node

play06:00

modules bin webpack right that's where

play06:04

it's

play06:05

at let see does it give me the

play06:10

version yeah gives me some information

play06:12

okay um so let's run it--watch

play06:17

um this will leave it running and it's

play06:20

going to watch for changes-- config and

play06:22

we're going to point to our config web

play06:24

pack. death. Js

play06:29

okay and you see it

play06:33

um copied these static assets here and

play06:37

then it

play06:40

generated content popup popup and

play06:43

background so let's take a look at our

play06:47

disc

play06:49

directory so if we go to disc and look

play06:53

at the files

play06:54

there um so we can see all these files

play06:57

so let's let's load it let's load it at

play07:01

this point we can try it out we can go

play07:04

to extensions I'm just going to blow

play07:06

away the previous one

play07:08

remove remove my Chrome extension yep

play07:12

all

play07:15

good and then we're going to we we're in

play07:18

Chrome extensions developer mode we're

play07:20

going to click load unpacked we're going

play07:23

to

play07:24

find the disc directory that we just

play07:27

created and we're going to select

play07:32

it's

play07:33

loaded um we're going to go here and pin

play07:36

it my Chrome

play07:40

extension

play07:43

um so we click on this it looks like um

play07:48

looks like it's loaded correctly um

play07:50

before we do any additional testing

play07:51

let's just move

play07:53

on to

play07:56

typescript uh so typescript

play08:00

basically is a superet of JavaScript

play08:02

that adds static

play08:04

typing uh and other

play08:08

features basically it is highly

play08:10

recommended to use typescript to catch

play08:12

errors early and improve quality because

play08:15

it relies on um types so you when you're

play08:20

coding and compiling using a webpack

play08:24

you're less likely to make mistakes so

play08:27

in the end you end up with higher

play08:29

quality code and you catch mistakes

play08:33

earlier all right so let's jump in into

play08:36

adding

play08:38

typescript let's stop this server we're

play08:40

going to come back to it

play08:42

later we're going to we're going to

play08:44

install also de development dependencies

play08:47

we're going to typescript we're going to

play08:49

add a recommended typescript

play08:52

configuration um TS node so typescript

play08:55

support for node remember we installed

play08:57

node as one of our prerequisites we we

play08:59

didn't install it we it's a prerequisite

play09:01

uh and this allows

play09:03

node um to use typescript and

play09:06

specifically we need it because we're

play09:08

going to use typescript for a webpack

play09:10

configuration right if we're going

play09:12

typescript might as well use typescript

play09:14

for everything we can uh typescript

play09:17

loader is a loader for webpack so it

play09:20

allows webpack to bundle typescript

play09:24

files and then finally this types Chrome

play09:28

it's a type definition right

play09:31

so um sometimes you are using a

play09:34

JavaScript library and a type definition

play09:37

adds types U that you

play09:39

need so this allows you to use type

play09:43

checking in your

play09:45

code so we're going to add type checking

play09:48

for our

play09:50

Chrome uh Chrome

play09:52

code that we're

play09:54

using all right let's install

play10:00

okay so next thing we're going to do is

play10:02

we're going to add the typescript

play10:06

configuration so typescript

play10:08

configuration is in TS config.js

play10:13

file and we're going to basically use

play10:15

the recommended configuration but in in

play10:17

addition to that we're going to add one

play10:19

more thing we're going to enable Source

play10:21

Maps so a source map maps The

play10:24

Source back to our generated Javascript

play10:27

file and I will show the this later how

play10:29

this works um but basically in order to

play10:33

map in order to debug our code in the

play10:36

browser um it's useful to have a source

play10:39

map because then it's a one to map map

play10:41

between the code we see here in our

play10:43

development environment and what we're

play10:45

debugging in the Chrome

play10:47

browser all right and that's all we need

play10:49

for TS

play10:51

config so now let's uh convert our

play10:55

webpack configurations which we just

play10:57

created from uh JavaScript to typescript

play11:01

so we just basically rename

play11:03

them uh refactor

play11:06

rename to typescript we're just going to

play11:09

rename all of

play11:11

them to

play11:14

typescript to the TS

play11:18

extension and and then we're going to

play11:20

mix uh fix them up a little bit real

play11:23

time so let's see

play11:25

common um so this is Javascript syntax

play11:29

so let's use

play11:32

the um typescript syntax let's

play11:36

see let's do

play11:40

that um and then we're not going to use

play11:43

this module exports we're going to use

play11:44

the modern uh export default syntax so

play11:48

let's just call this

play11:51

config and we're going to give it a type

play11:54

this is web pack. configuration

play11:57

type uh so now now you know this type is

play12:01

is checking to make sure we're using you

play12:04

know the proper proper types here okay

play12:08

um and then we're going to use this

play12:10

syntax export default

play12:13

config all right that's it for uh the

play12:16

common. TS let's move on to def.

play12:22

TS

play12:25

um let's change this

play12:32

do

play12:34

this we're getting the config from web

play12:37

pack. common

play12:40

um we're going to call it common

play12:44

here to be

play12:49

consistent well let's just uh let's just

play12:52

call it config for Simplicity let not

play12:55

create a new

play12:57

name but basically it merges configs and

play12:59

then we we can add a type here we can

play13:02

tell this that this is a configuration

play13:05

type right I just noticed something I'm

play13:08

specifically importing this

play13:10

configuration type for webpack which

play13:13

means I can

play13:14

[Music]

play13:15

probably do this

play13:19

here because the only thing I'm using is

play13:23

configuration yeah so this works as well

play13:29

okay what do we have here and then we're

play13:32

going to use the new uh export syntax

play13:37

so and then we're going to export

play13:40

default

play13:42

merged okay update the production

play13:45

similar

play13:48

way everything good

play13:54

okay um

play13:59

and then another thing another thing so

play14:02

now we can uh we going are we ready to

play14:04

run

play14:06

it yeah let's run it because I want to

play14:09

run it and I want to show one more thing

play14:11

that we can do to package.json so let's

play14:14

run

play14:17

it okay so now we are here and we're

play14:21

just going to point it to typescript

play14:23

let's

play14:27

see uh

play14:37

okay looks like there's no changes here

play14:41

which is expected but let me blow this

play14:47

away rerun

play14:53

this yep all the files are there um all

play14:57

right so you see how we're using this

play15:01

this long command here so we can be

play15:03

simplified by using the scripts feature

play15:06

or in our

play15:08

package. Json file so here we can add

play15:12

scripts and it's already recommending me

play15:15

what to add

play15:17

here um yes we're going to add

play15:23

build web

play15:25

pack but we're just going to point the

play15:29

config and this is now a typescript

play15:31

config

play15:32

previously it was JavaScript and then

play15:34

we're going to add a

play15:37

start webpack

play15:40

d-at D- config okay this is good um so

play15:46

now instead of uh using this long

play15:49

command line we can just run NP npm Run

play15:53

start to do the same

play15:57

thing looks like I have a typo

play16:06

here web pack Dev here and this is

play16:11

prod okay let's try it again so this

play16:19

is I I made a mistake build

play16:23

start start is

play16:26

Dev build is PR got to be careful

play16:33

here let's just double check to make

play16:35

sure it's still

play16:38

working start using Dev

play16:42

config

play16:43

watching and npm run buil use the

play16:46

production

play16:48

config and while we're here let's look

play16:50

at the production config um the map

play16:53

files are separate and let's just

play16:57

uh just look at the back background.js

play16:59

file you see this is minified right

play17:02

spaces all sprit um stripped out it's

play17:05

all in one line right so this is

play17:06

optimized for

play17:10

production okay so now we're actually

play17:13

ready to convert the actual JavaScript

play17:18

files that we had to typescript so let's

play17:20

go ahead and just uh rename

play17:25

them typescript

play17:29

Factory name

play17:33

typescript Factory

play17:37

name

play17:40

typescript um it's probably going to

play17:42

give us some errors okay so let's see

play17:45

what what my ID is

play17:47

thinking says duplicate function

play17:50

implementation well it's because we're

play17:51

using it multiple files um I'm actually

play17:54

not sure if this is actually going to

play17:55

cause issues

play18:02

you know just for experiment purposes

play18:05

let's just try it let's just try

play18:07

building as is and see what

play18:10

happens

play18:12

um before we do that we need

play18:15

to update some

play18:20

things yeah let's let's update our web

play18:22

pack and then see what happens if we

play18:24

just build this with

play18:26

errors um pretty sure it's not going to

play18:28

work

play18:31

uh so to update

play18:32

this first of all we need to change

play18:36

these entries to typescript then we're

play18:39

going to add

play18:42

the uh TS loader

play18:46

module for our webpack to

play18:49

actually resolve typescript files using

play18:53

this TS loader right and this TS loader

play18:56

simply points to the T typescript

play18:58

compiler that we

play19:01

installed um so we

play19:03

can try building and then we should see

play19:06

some errors right so

play19:09

npm um run

play19:12

build let's

play19:15

see yeah all these air so let's go go

play19:19

ahead and fix

play19:22

them um duplicate function so let's

play19:25

create a new file called common

play19:29

.ts and we're going to move this over in

play19:33

that that

play19:35

file i'ms and they're going to export

play19:40

this export this is Boolean yeah that's

play19:45

a good

play19:47

idea uh here we don't need this use

play19:50

trick we can

play19:54

import from common right

play19:59

then we're using it here this looks

play20:02

clean let's move on to content

play20:10

file uh okay we need to type

play20:21

here blur

play20:25

element see this is it's uh um needs a

play20:30

typee here as

play20:34

well this is our our only other error

play20:42

okay this is HTML

play20:51

element there we

play20:56

go it's now complaining that this could

play20:58

be null so this code we can let's fix it

play21:01

a little bit

play21:05

um basically this is now I mean this is

play21:08

potential bug right it's telling me when

play21:10

we get to this point this parent could

play21:12

be

play21:16

null because over in this function I'm

play21:18

using it but if it's null it's going to

play21:20

I mean this is actually a bug right so

play21:22

it found a real

play21:25

bug so let's do a check here for now if

play21:28

parent equals

play21:33

null

play21:36

return now we don't need to check

play21:43

here and yeah this we good is this file

play21:48

good okay let's go to the last

play21:52

one set badge text we're going to import

play21:54

it

play22:02

yep

play22:04

um

play22:07

basically it's also saying it could be

play22:10

null so we know it will not be null

play22:14

because this is our code right we have

play22:16

this

play22:17

element

play22:20

um because this enabled element ID is in

play22:23

our popup HTML file over here enabled

play22:28

so we know that's not going to be null

play22:31

so if we just

play22:32

do

play22:34

as HTML input element to fix that and

play22:38

same for this item value

play22:42

as HTML input element

play22:47

okay

play22:49

um I think that I think we are ready to

play22:52

run this let's let's let's do

play22:55

it npm run start you also just do npm

play23:00

start um start is a special keyword for

play23:05

npm it just goes and looks for the

play23:08

script that's called

play23:11

start okay code successfully generated

play23:14

all right so let's do some playing

play23:16

around all right

play23:19

let's go

play23:24

um we don't you don't need to reload it

play23:27

but um I don't think you need to reload

play23:29

it but I did anyway all right so let's

play23:31

do a couple

play23:34

things um so we have this pop up here so

play23:38

let's modify

play23:40

it let go over here HTML and we're going

play23:44

to add

play23:46

another thing called item

play23:50

two let's see what

play23:53

happens see

play23:57

it it it

play23:59

updated the pop up. HTML here which

play24:03

means if I go here and I click on it

play24:06

again I see I see it's being

play24:10

updated and we can test our

play24:15

um JavaScript so let's update this file

play24:17

Let's

play24:20

uh add some exclamation

play24:24

points and we

play24:26

see that generate it knows right it's

play24:30

using buling so it knows that that um

play24:34

that common file isn't used is used over

play24:37

here in these two

play24:39

files so it updated it in real

play24:42

time so now it's still the old one

play24:45

because we

play24:47

haven't hasn't run yet okay now it run

play24:50

we see the new code so see it's uh it's

play24:52

updating in real time so it's really

play24:54

handy so now move on to debugging so um

play24:58

there's three parts right so you can

play25:00

debug them in separate way uh background

play25:02

script with the service

play25:04

worker um the common one is just on the

play25:08

page and the popup is over here right

play25:11

click inspect

play25:13

popup here we have the popup we have the

play25:17

code here if we go to

play25:19

sources go to microme extension

play25:23

source and now see common and popup this

play25:26

is the exact same code

play25:30

code um that we had that we have in our

play25:34

development

play25:38

environment

play25:39

right let popup code yep exact same code

play25:44

so I can add

play25:47

a breako here and then I can do

play25:51

something that triggers this breakpoint

play25:54

so I can examine the the values

play26:07

um over here if I look at this

play26:11

event I can examine things here uh can

play26:14

step through it so all the debug stuff

play26:16

so you know great great for debugging uh

play26:20

bugs in your

play26:21

extension all right um one more thing I

play26:25

want to mention um is that

play26:29

the Chrome type that we added was Global

play26:33

so if I go back to my development

play26:35

environment and I am using Chrome here

play26:38

right Chrome storage sync so this is a

play26:41

global type but and you see we did not

play26:43

import anything for that type it's a

play26:45

global type um so for some idees you

play26:49

might need to explicitly add this so for

play26:52

example I'm using webstorm so here I had

play26:54

to go webstorm settings languages

play26:57

framework work JavaScript libraries and

play27:01

actually add it here or we might need to

play27:05

download it if it's not

play27:09

present um because it's a global type

play27:12

you know you might need your development

play27:14

environment to be aware of this chrome

play27:21

type all right this has been a pretty

play27:24

long video and thanks for sticking with

play27:26

it um

play27:28

in the next part we will

play27:31

continue uh adding features and

play27:34

development tools to our Chrome

play27:37

extension

Rate This

5.0 / 5 (0 votes)

Ähnliche Tags
Расширения ChromeWebpackTypeScriptРуководствоПрограммированиеJavaScriptТипизацияКодированиеРазвертывание
Benötigen Sie eine Zusammenfassung auf Englisch?