Add webpack and TypeScript to a Chrome extension (2024)
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
🛠 Настройка 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 для конкретной настройки разработки.
🔧 Установка и настройка webpack для разработки
В этом параграфе описывается процесс установки и настройки webpack для разработки Chrome расширения. Создается файл webpack.dev.js с настройками для режима разработки, включая использование inline-карты исходников для упрощения отладки. Также создается файл webpack.prod.js для продакшн-настройки, который включает в себя различные оптимизации для производственной среды. После настройки, webpack запускается с использованием команды 'watch', которая обеспечивает автоматическое обновление сборки при внесении изменений в исходные файлы. Производится проверка работы расширения в Chrome, удаляется старый экземпляр расширения и загружается новый, сгенерированный webpack.
💡 Внедрение TypeScript в проект
В этом разделе рассказывается о преимуществах использования TypeScript в проекте Chrome расширения для улучшения качества кода и раннего выявления ошибок. Устанавливаются необходимые пакеты для работы с TypeScript, включая сам TypeScript, TS-node для поддержки TypeScript в Node.js и typescript-loader для webpack. Также устанавливаются типы для Chrome, чтобы иметь доступ к типам API Chrome в TypeScript-проекте. Создается конфигурационный файл tsconfig.json с рекомендуемыми настройками и включением Source Maps для упрощения отладки. Далее переписываются существующие конфигурационные файлы webpack на TypeScript и исправляются возникающие ошибки.
⚙️ Улучшение конфигурации и добавление скриптов в package.json
В этом параграфе описывается процесс оптимизации и упрощения команд webpack с помощью добавления скриптов в файл package.json. Изменяются скрипты для запуска webpack в режиме разработки и продакшена, исправляются опечатки и проверяется корректность работы сборки. Также обсуждается перенос исходных JavaScript-файлов в TypeScript, включая исправление ошибок, возникающих из-за дублирования функций и обновления импортов. После внесения изменений и исправления ошибок, проверяется успешность сборки и функционирования расширения в браузере.
🕵️♂️ Отладка и дальнейшее развитие расширения
В заключительном разделе видео рассматривается отладка различных частей Chrome расширения с использованием инструментов разработчика в браузере. Показывается, как можно установить точки останова и отлаживать код, используя Source Maps, которые были включены в настройках TypeScript. Также обсуждается необходимость добавления типов Chrome в среду разработки для корректного определения типов API Chrome. Наконец, автор видео подводит итоги и анонсирует, что в следующих частях курса продолжатся добавление новых функций и инструментов разработки в проект Chrome расширения.
Mindmap
Keywords
💡Chrome расширение
💡Webpack
💡TypeScript
💡npm
💡package.json
💡Бандлинг
💡Конфигурация webpack
💡Статичные ресурсы
💡Типизация
💡Инструменты разработки
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
this is the second part of our series on
creating a production ready Chrome
extension so in this video we will add
the webpack build tool and
typescript to our project that we
created in the previous video so let's
uh jump into into some prerequisites so
first we need to make sure we have no JS
which is a JavaScript runtime
installed um we will need it to run
webpack and then any future development
tools We'll add and we also need npm
which is a package manager for
JavaScript so for example I can find the
web pack pack web pack package here so
in order to check whether these are
installed we just do um node DV to see
which version we have installed npm DV
to see which version of npm we have
installed okay so let's jump in so we
have our code from uh the previous
video we got we got our basic Chrome
extension with all the files and source
and first thing we're going to do is
we're going to create a package.json
file so it it holds uh basically project
information and dependency information
we could just run npm init to create
that file npm init um but in this case
we'll just do it manually so let's
create a new file package.json
and then we'll put some text in it
nothing
special okay so let's move on to uh
adding
webpack so what is webpack well
essentially webpack is a bundler it
create it takes multiple files with
dependency in them and then in them and
then creates a single
file um so in our
case we're going to have multiple
JavaScript files that will then be
bundled into a single Javascript file
now in addition to this bundling it also
does some other things like uh
compression and minification um for
performance
reasons so let's uh let's install
it so we're going to run these commands
we're going to install webpack itself
webpack CLI because we're going to be
running it from the command line uh web
pack merge merge is going to merge our
kind of common config and our
development config because we're going
to have two configurations one for
development one for production and then
this copy plugin basically just for
copying static assets so let's install
all these using this
command so we can look at what happened
in our
directory see we now have a new package
do- log. jent file which was created by
npm right and it holds the exact
versions of all these dependencies and
their
subpena
package.json so we see uh the versions
that got
installed all right let's move on to the
configuration so configuring webpack um
by default it doesn't really require
configuration but because we're using a
chrome extension and uh Chrome extension
has three parts uh so we effectively is
going to have three different
bundles um so we need to we need to
configure all of that so let's go ahead
and create a new file uh we're going to
create a file called Web pag.
common.js that's where our common
configuration is going to
be um so we're going to have the
background script content script and the
popup scripts so these are the three
bundles we're going to be creating
they're all going to go into this this
directory so previously we were loading
everything from
Source now uh we're going to be loading
from
this um and
then we're going to have a static folder
so some of these files we're not going
to mess with at this point so we're
going to move them to a static directory
so let's create a new directory called
Static and let's move
manifest um manifest Json and these
popup CSS popup HTML let's move them
into
static okay um so we have the common
file now we're going to create
a um a development config that's going
to point to this common config so this
common config is going to be consumed by
both development and production config
so let's create
new file webpack dod. JS that's going to
be our development
config so we're going to put development
mode here and we're going to use an
inline Source map um inline Source map
basically just puts maps are generated
uh the generated JavaScript back to our
original JavaScript and it all does in
the in in the single file so this is
often used um during development using
an inline Source
M um and then we add our uh production
config
we're going to add a production
config this our production config okay
so where we are now we've
refactored are we ready to run the web
pack let's let's try to run
it go back to our
terminal and um we installed weback so
by default it can be run by from node
modules bin webpack right that's where
it's
at let see does it give me the
version yeah gives me some information
okay um so let's run it--watch
um this will leave it running and it's
going to watch for changes-- config and
we're going to point to our config web
pack. death. Js
okay and you see it
um copied these static assets here and
then it
generated content popup popup and
background so let's take a look at our
disc
directory so if we go to disc and look
at the files
there um so we can see all these files
so let's let's load it let's load it at
this point we can try it out we can go
to extensions I'm just going to blow
away the previous one
remove remove my Chrome extension yep
all
good and then we're going to we we're in
Chrome extensions developer mode we're
going to click load unpacked we're going
to
find the disc directory that we just
created and we're going to select
it's
loaded um we're going to go here and pin
it my Chrome
extension
um so we click on this it looks like um
looks like it's loaded correctly um
before we do any additional testing
let's just move
on to
typescript uh so typescript
basically is a superet of JavaScript
that adds static
typing uh and other
features basically it is highly
recommended to use typescript to catch
errors early and improve quality because
it relies on um types so you when you're
coding and compiling using a webpack
you're less likely to make mistakes so
in the end you end up with higher
quality code and you catch mistakes
earlier all right so let's jump in into
adding
typescript let's stop this server we're
going to come back to it
later we're going to we're going to
install also de development dependencies
we're going to typescript we're going to
add a recommended typescript
configuration um TS node so typescript
support for node remember we installed
node as one of our prerequisites we we
didn't install it we it's a prerequisite
uh and this allows
node um to use typescript and
specifically we need it because we're
going to use typescript for a webpack
configuration right if we're going
typescript might as well use typescript
for everything we can uh typescript
loader is a loader for webpack so it
allows webpack to bundle typescript
files and then finally this types Chrome
it's a type definition right
so um sometimes you are using a
JavaScript library and a type definition
adds types U that you
need so this allows you to use type
checking in your
code so we're going to add type checking
for our
Chrome uh Chrome
code that we're
using all right let's install
okay so next thing we're going to do is
we're going to add the typescript
configuration so typescript
configuration is in TS config.js
file and we're going to basically use
the recommended configuration but in in
addition to that we're going to add one
more thing we're going to enable Source
Maps so a source map maps The
Source back to our generated Javascript
file and I will show the this later how
this works um but basically in order to
map in order to debug our code in the
browser um it's useful to have a source
map because then it's a one to map map
between the code we see here in our
development environment and what we're
debugging in the Chrome
browser all right and that's all we need
for TS
config so now let's uh convert our
webpack configurations which we just
created from uh JavaScript to typescript
so we just basically rename
them uh refactor
rename to typescript we're just going to
rename all of
them to
typescript to the TS
extension and and then we're going to
mix uh fix them up a little bit real
time so let's see
common um so this is Javascript syntax
so let's use
the um typescript syntax let's
see let's do
that um and then we're not going to use
this module exports we're going to use
the modern uh export default syntax so
let's just call this
config and we're going to give it a type
this is web pack. configuration
type uh so now now you know this type is
is checking to make sure we're using you
know the proper proper types here okay
um and then we're going to use this
syntax export default
config all right that's it for uh the
common. TS let's move on to def.
TS
um let's change this
do
this we're getting the config from web
pack. common
um we're going to call it common
here to be
consistent well let's just uh let's just
call it config for Simplicity let not
create a new
name but basically it merges configs and
then we we can add a type here we can
tell this that this is a configuration
type right I just noticed something I'm
specifically importing this
configuration type for webpack which
means I can
[Music]
probably do this
here because the only thing I'm using is
configuration yeah so this works as well
okay what do we have here and then we're
going to use the new uh export syntax
so and then we're going to export
default
merged okay update the production
similar
way everything good
okay um
and then another thing another thing so
now we can uh we going are we ready to
run
it yeah let's run it because I want to
run it and I want to show one more thing
that we can do to package.json so let's
run
it okay so now we are here and we're
just going to point it to typescript
let's
see uh
okay looks like there's no changes here
which is expected but let me blow this
away rerun
this yep all the files are there um all
right so you see how we're using this
this long command here so we can be
simplified by using the scripts feature
or in our
package. Json file so here we can add
scripts and it's already recommending me
what to add
here um yes we're going to add
build web
pack but we're just going to point the
config and this is now a typescript
config
previously it was JavaScript and then
we're going to add a
start webpack
d-at D- config okay this is good um so
now instead of uh using this long
command line we can just run NP npm Run
start to do the same
thing looks like I have a typo
here web pack Dev here and this is
prod okay let's try it again so this
is I I made a mistake build
start start is
Dev build is PR got to be careful
here let's just double check to make
sure it's still
working start using Dev
config
watching and npm run buil use the
production
config and while we're here let's look
at the production config um the map
files are separate and let's just
uh just look at the back background.js
file you see this is minified right
spaces all sprit um stripped out it's
all in one line right so this is
optimized for
production okay so now we're actually
ready to convert the actual JavaScript
files that we had to typescript so let's
go ahead and just uh rename
them typescript
Factory name
typescript Factory
name
typescript um it's probably going to
give us some errors okay so let's see
what what my ID is
thinking says duplicate function
implementation well it's because we're
using it multiple files um I'm actually
not sure if this is actually going to
cause issues
you know just for experiment purposes
let's just try it let's just try
building as is and see what
happens
um before we do that we need
to update some
things yeah let's let's update our web
pack and then see what happens if we
just build this with
errors um pretty sure it's not going to
work
uh so to update
this first of all we need to change
these entries to typescript then we're
going to add
the uh TS loader
module for our webpack to
actually resolve typescript files using
this TS loader right and this TS loader
simply points to the T typescript
compiler that we
installed um so we
can try building and then we should see
some errors right so
npm um run
build let's
see yeah all these air so let's go go
ahead and fix
them um duplicate function so let's
create a new file called common
.ts and we're going to move this over in
that that
file i'ms and they're going to export
this export this is Boolean yeah that's
a good
idea uh here we don't need this use
trick we can
import from common right
then we're using it here this looks
clean let's move on to content
file uh okay we need to type
here blur
element see this is it's uh um needs a
typee here as
well this is our our only other error
okay this is HTML
element there we
go it's now complaining that this could
be null so this code we can let's fix it
a little bit
um basically this is now I mean this is
potential bug right it's telling me when
we get to this point this parent could
be
null because over in this function I'm
using it but if it's null it's going to
I mean this is actually a bug right so
it found a real
bug so let's do a check here for now if
parent equals
null
return now we don't need to check
here and yeah this we good is this file
good okay let's go to the last
one set badge text we're going to import
it
yep
um
basically it's also saying it could be
null so we know it will not be null
because this is our code right we have
this
element
um because this enabled element ID is in
our popup HTML file over here enabled
so we know that's not going to be null
so if we just
do
as HTML input element to fix that and
same for this item value
as HTML input element
okay
um I think that I think we are ready to
run this let's let's let's do
it npm run start you also just do npm
start um start is a special keyword for
npm it just goes and looks for the
script that's called
start okay code successfully generated
all right so let's do some playing
around all right
let's go
um we don't you don't need to reload it
but um I don't think you need to reload
it but I did anyway all right so let's
do a couple
things um so we have this pop up here so
let's modify
it let go over here HTML and we're going
to add
another thing called item
two let's see what
happens see
it it it
updated the pop up. HTML here which
means if I go here and I click on it
again I see I see it's being
updated and we can test our
um JavaScript so let's update this file
Let's
uh add some exclamation
points and we
see that generate it knows right it's
using buling so it knows that that um
that common file isn't used is used over
here in these two
files so it updated it in real
time so now it's still the old one
because we
haven't hasn't run yet okay now it run
we see the new code so see it's uh it's
updating in real time so it's really
handy so now move on to debugging so um
there's three parts right so you can
debug them in separate way uh background
script with the service
worker um the common one is just on the
page and the popup is over here right
click inspect
popup here we have the popup we have the
code here if we go to
sources go to microme extension
source and now see common and popup this
is the exact same code
code um that we had that we have in our
development
environment
right let popup code yep exact same code
so I can add
a breako here and then I can do
something that triggers this breakpoint
so I can examine the the values
um over here if I look at this
event I can examine things here uh can
step through it so all the debug stuff
so you know great great for debugging uh
bugs in your
extension all right um one more thing I
want to mention um is that
the Chrome type that we added was Global
so if I go back to my development
environment and I am using Chrome here
right Chrome storage sync so this is a
global type but and you see we did not
import anything for that type it's a
global type um so for some idees you
might need to explicitly add this so for
example I'm using webstorm so here I had
to go webstorm settings languages
framework work JavaScript libraries and
actually add it here or we might need to
download it if it's not
present um because it's a global type
you know you might need your development
environment to be aware of this chrome
type all right this has been a pretty
long video and thanks for sticking with
it um
in the next part we will
continue uh adding features and
development tools to our Chrome
extension
関連動画をさらに表示
ИЗУЧИТЕ ГЛАВНУЮ НЕЙРОСЕТЬ МИРА от Б до Ю
STALKER Anomaly Basic Addon Tutorial - Creating/Editing Weapons
Обновленный Selenium и работа с прокси | Python, Selenium и proxy | Подмена IP адреса
SIMPLE Way I Make $1,000 Daily With Chat GPT / YouTube (FOR FREE!)
Setting Up Vite and React for Chrome Extension Development
История Барабанной Установки. Русский перевод. 8 серий.
5.0 / 5 (0 votes)