Форум программистов, компьютерный форум, киберфорум
8Observer8
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  

Browserify TypeScript + Bonus: UglifyJS

Запись от 8Observer8 размещена 21.02.2019 в 18:32
Показов 1578 Комментарии 0
Метки typescript

Blog content

It is the most common problem for anyone who starts to study TS. They cannot include a few ".js" files after compilation to <script> tags in "index.html".

It is very simple in JS. You have two files in JS and you can include them in "index.html"

PHP/HTML
1
2
3
4
5
6
7
8
<html>
 
<head>
    <script src="js/sayHello.js"></script>
    <script src="js/main.js"></script>
</head>
 
</html>
sayHello.js

JavaScript
1
2
3
4
function sayHello(name)
{
    console.log("Hello, " + name);
}
main.js

JavaScript
1
2
3
4
5
function main()
{
    sayHello("Ivan");
}
window.onload = main;
Output:
Hello, Ivan
But if you rewrite these files in TypeScript:

sayHello.ts

JavaScript
1
2
3
4
export function sayHello(name: string): void
{
    console.log("Hello, " + name);
}
main.ts

JavaScript
1
2
3
4
5
6
7
import { sayHello } from './sayHello';
 
function main(): void
{
    sayHello("Ivan");
}
window.onload = main;
And if you compile them to JavaScript:

tsc ts/main.ts ts/sayHello.ts --outDir "dist"
You cannot just include this files in "index.html":

PHP/HTML
1
2
3
4
5
6
7
8
<html>
 
<head>
    <script src="dist/sayHello.js"></script>
    <script src="dist/main.js"></script>
</head>
 
</html>
You will see this errors in the browser debug console:

Uncaught ReferenceError: exports is not defined
at sayHello.js:2

Uncaught ReferenceError: exports is not defined
at main.js:2
There are a few ways to solve this problem:
  • You can concatenate all generated ".js" files in one bundle.js file using: Webpack, Gulp, Grund and so on. For example, see this official instruction: Gulp - TypeScript
  • You can compile to AMD modules and use RequreJS to load them. For example, see my instruction: A few TypeScript files on Sandbox
  • You can use Browserify to concatenate all generated ".js" files in one bundle.js file

I will show you how to use Browserify. Install Browserify using this command:
npm install browserify -g
You can create bundle.js using this command:

browserify dist/main.js dist/sayHello.js -o dist/bundle.js
You will see "bundle.js" in the "dist" folder. Now you can include "bundle.js" in "index.html" using <script> tag:

PHP/HTML
1
2
3
4
5
6
7
<html>
 
<head>
    <script src="dist/bundle.js"></script>
</head>
 
</html>
Open "index.html" file in a browser and you will see "Hello, Ivan" in the browser debug console.

Bonus. UglifyJS

You can install uglifyjs:

npm install uglify-js -g
And compress your "bundle.js" to "bundle.min.js":

uglifyjs dist/bundle.js -o dist/bundle.min.js
Do not forget to change a script name from "bundle.js" to "bundle.min.js" in "index.html":

index.html

PHP/HTML
1
2
3
4
5
6
7
<html>
 
<head>
    <script src="dist/bundle.min.js"></script>
</head>
 
</html>
Метки typescript
Размещено в Без категории
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
Всего комментариев 0
Комментарии
 
Новые блоги и статьи
[golang] Двоичная куча, min-heap
alhaos 20.05.2026
Двоичная куча Двоичная куча — структура данных, которая всегда держит самый важный элемент наготове. Представьте очередь к хилеру в игре, и очередь из игроков в приоритете те у кого меньше. . .
[golang] Breadth-First Search
alhaos 19.05.2026
BFS (Breadth-First Search) — это базовый алгоритм обхода графа в ширину, который поуровнево исследует все связанные вершины. Он начинает с выбранной точки и проверяет всех соседей, прежде чем. . .
[golang] Алгоритм «Хак Госпера»
alhaos 17.05.2026
Алгоритм «Хак Госпера» Хак Госпера (Gosper's Hack) — алгоритм нахождения следующего по величине числа с тем же количеством установленных бит. Придуман Биллом Госпером в 1970-х, опубликован в. . .
Рисование бинарного древа до 6-го колена на js, svg.
russiannick 17.05.2026
<svg width="335" height="240" viewBox="0 0 335 240" fill="#e5e1bb"> <style> <!]> </ style> <g id="bush"> </ g> </ svg> function fn(){ let rost;/ / высота древа let xx=165,yy=210,w=256;
FSharp: interface of module
DevAlt 16.05.2026
Интерфейс модуля F# позволяет управлять доступностью членов, содержащихся в реализации модуля. По-умолчанию все члены модуля доступны: module Foo let x = 10 let boo () = printfn "boo" . . .
Хитросплетение родственных связей пантеона греческих богов.
russiannick 14.05.2026
Однооконник, позволяющий узреть и изучить отдельных героев древней Греции. <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible". . .
[golang] Угол между стрелками часов
alhaos 12.05.2026
По заданным значениям часа и минуты необходимо определить значение меньшего угла между стрелками аналогового циферблата часов. import "math" func angleClock(hour int, minutes int) float64 { . . .
Debian 13: Установка Lazarus QT5
ВитГо 09.05.2026
Эта инструкция моя компиляция инструкций volvo https:/ / www. cyberforum. ru/ blogs/ 203668/ 10753. html и его же старой инструкции по установке Lazarus с gtk2. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru