В этом руководстве рассказывается, как настроить html2js-loader и webpack. Если вы не знаете, что делает html2js, вы можете прочитать эту запись в блоге или воспользоваться инструментом онлайн-конвертера.
Для начала вы можете воспользоваться следующей инструкцией.
npm init
npm i -D html2js-loader webpack webpack-cli
или клонируйте репозиторий учебника.
git clone https://github.com/LesterGallagher/html2js-loader-demo-tutorial.git
Когда загрузчик и веб-пакет закончат установку, добавьте в свои скрипты следующую строку:
"scripts": {
"start": "webpack --config webpack.config.js --watch"
}
Создайте файл «webpack.config.js».
// webpack.config.js
const path = require('path');
module.exports = { context: __dirname, entry: path.resolve(__dirname, 'src/index'), mode: 'development', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, module: { rules: [{ test: /\.html$/, use: { loader: 'html2js-loader', options: { // defaults:
// trimWhitespace: false, // removeComments: false, // skipEmptyTextNodes: false } } }] } }
Теперь создайте папку с именем «dist» и добавьте файл «index.html»:
<!-- dist/index.html -->
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>html2js loader tutorial</title> </head> <body> <script src="bundle.js"></script> </body> </html>
Также добавьте папку «src» с файлом «index.js», содержащим:
// src/index.js
document.write('<h1>Hello World</h1>');
Вот и все, мы закончили настройку проекта, вы можете запустить «npm start», чтобы следить за изменениями и собирать свой проект.
npm start
Откройте файл «index.html» в своем любимом браузере (например, Chrome), и вы должны увидеть текст «Hello World».
Чтобы использовать загрузчик, мы создаем html-файл в папке src (я назову его «posts.html» со следующим содержимым).
<!-- src/posts.html -->
<h1>Blog Posts</h1>
<section class="posts" itemscope itemtype="http://schema.org/Blog"> <article itemprop="blogPost"> <img class="post-image" itemprop="image" src="https://esstudio.site/uploads/simple%20draggable%20elements2.gif" alt=""Create draggable elements with Javascript" Thumbnail"> <h2 class="post-title">Create draggable elements with Javascript</h2> <p><small class="post-date">01 NOVEMBER 2018</small></p> <a target="_blank" href="https://esstudio.site/2018/11/01/create-draggable-elements-with-javascript.html">View more...</a> </article> <article itemprop="blogPost"> <img class="post-image" itemprop="image" src="https://esstudio.site/uploads/giphy.gif" alt=""Lazy loading images with Javascript" Thumbnail"> <h2 class="post-title">Lazy loading images with Javascript</h2> <p><small class="post-date">01 NOVEMBER 2018</small></p> <a target="_blank" href="https://esstudio.site/2018/11/01/lazyloading-images-with-javascript.html">View more...</a> </article> <article itemprop="blogPost"> <img class="post-image" itemprop="image" src="https://esstudio.site/uploads/binaryheap.png" alt=""Implementing Binary Heaps with Javascript" Thumbnail"> <h2 class="post-title">Implementing Binary Heaps with Javascript</h2> <p><small class="post-date">31 OCTOBER 2018</small></p> <a target="_blank" href="https://esstudio.site/2018/10/31/implementing-binary-heaps-with-javascript.html">View more...</a> </article> <article itemprop="blogPost"> <img class="post-image" itemprop="image" src="https://esstudio.site/uploads/rssreader.jpg" alt=""Creating an Atom feed reader with Javascript" Thumbnail"> <h2 class="post-title">Creating an Atom feed reader with Javascript</h2> <p><small class="post-date">30 OCTOBER 2018</small></p> <a target="_blank" href="https://esstudio.site/2018/10/30/creating-an-atom-feed-reader-with-javascript.html">View more...</a> </article> </section>
Давайте откроем «src/index.js» и заменим предыдущий контент на:
// src/index.js
const createPosts = require('./posts.html');
document.body.appendChild(createPosts());
Некоторые необязательные CSS:
/* dist/style.css */
* { box-sizing: border-box; }
html { font-family: sans-serif; }
article { width: 25%; float: left; padding: 10px; }
img { max-width: 100%; }
h1 { padding: 10px; }
@media screen and (max-width: 1000px) { article { width: 50%; } }
@media screen and (max-width: 500px) { article { width: 100%; } }
Ресурсы:
- JavaScript за 24 часа
- HTML, CSS, ES6 все в одном
- Практическое руководство по созданию веб-приложений с использованием React
- Изучение регулярных выражений
- Веб-разработка на Node.js, MongoDB и Angular
InformIT eBook Store предлагает большое количество электронных книг на самые разные темы. Я определенно рекомендую их.
Отличные курсы:
- Javascript для начинающих за 3 часа
- Основные блоки веб-разработки на JavaScript
- Мобильный UI и UX дизайн
- Создание веб-приложений с помощью React
- Начиная с углового 4
- Программирование на C# (рекомендуется)
- Еще курсы по веб-разработке
Quickstart предлагает большое количество (онлайн) курсов по веб-разработке (Используйте код LSOFF50, чтобы получить скидку 50% ;p)