Не работает @import в gulp
Почему-то выбивает вот такую ошибку, никак не могу понять с чем это связано. Проверил все пути, вроде все нормально, а ошибка есть.
![]()
![]()
Компилятор SASS в CSS не может найти файл font-awesome.min.css. Попробуй в директиве @import убрать .css в конце. т.е. если у тебя @import «/app/example.css» отредактировать в «/app/example».
Попробуйте в импорте использовать одинарные кавычки вместо двойных @import ‘mixins’; @import ‘variables’;
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43304
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Getting import/export working ES6 style using Browserify + Babelify + Gulp = -5hrs of life
Web browsers have traditionally been quite slow to keep up with the times. Back in the early days, there was a huge surge of development of features (IE vs Netscape) all to gain the largest market share. This probably took the efforts to solidify web standard slightly backwards as developers simply has no choice but to support which ever browser was the most feature complete. Some of those features even became the pseudo-standard (or just quirks) like how CSS renders or even how HTML tags / attributes are to be used.
We’re now in 2016 and its a great time to be a developer… or so I thought… There’s a sense for the web community to really push the next iteration of standards HTML5, CSS3, ES6 (aka ES2015). Most browsers nowadays ship with (or have experimental) builds that involve unconfirmed standard features. This leads to a bit of quirks but documentation these days is very good so you know if you can rely on it or not (e.g: http://caniuse.com/).
HTML5 and CSS3 have caught up and really changed what’s possible on the web (I love animations and Browser API support). However one key element of the web still lags behind a bit in terms of uniformity and support; the next iteration of Javascript (an implementation of ECMAScript, the language specification) — ES6.
One recent example where I lost so much time is using the new ES6 ‘import’ and ‘export’ module syntax, which I took for granted when using boilerplates or templates made by others (e.g. React). In NodeJS, ‘require’ was such an easy way to modularise your code into files as well as the ability to treat these modules as libraries (via a package manager like npm). In the Browser, this thing just doesn’t exist. And if you think about it, its quite difficult to achieve. There’s been efforts to take care of this but they’ve always been a bit awkward and complicated (I’ve RequireJS before and it was always a pain to setup and ended up being extremely fragile).
Here comes Browserify, a library which lets you ‘require’ code/modules in the same manner as you do in Node. Basically ‘Node modules for the client’. But there’s a catch; you can’t simply do require(‘myModule’) in the browser, because where is the browser going to fetch that resource from? So you actually gotta include the module somewhere on the page. Thus we end up having to bundle the javascript and send it all down to the client. Easy, we’ve been doing this type of stuff for a while using Gulp so its easy to collect files and process them. So that’s using Browserify + Gulp to get ‘require()’ working on the client.
We haven’t gotten to the ES6 syntax ‘import’ and ‘export’ keywords are much nicer and substantially more powerful than require() is — albeit the syntax isn’t as uniform/straightforward as I’d like it to be. Anyway, now if we want to write our code in ES6, since the majority of browsers don’t yet fully support ES6, we need to transpile it into ES5 via a compiler called Babel. This tool is like a pre-compiler, it’ll scan your files, converting the ES6 syntax into ES5 equivalents. However there’s one problem; ‘require()’ is not even in the ES5 syntax… So even if we compile we can’t use it… Guess what, you need to use a tool which does understand require(), and Browserify does.
This leads us to Babel + Browserify + Gulp. Seems like a simple enough path right? Wrong… Browserify isn’t very good with Babel directly and so I found out that you gotta use another library called ‘Babelify’ >_> Anyway, its a transform tool which Browserify uses to convert ES6 to ES5 and then does the magical dependency resolution.
So… why did I suddenly lose 5 hours? Probably due to lack of proper research and understanding. But honestly, I think its due to the fact that there are just so many ways to do things that its hard to know where things go wrong or which way to take. This is one of the joys and frustrations that comes from working on the (literally) bleeding edge tools and features of the web. Its a shame that during my endless hunts there wasn’t as much concrete documentation regarding what everything is and how it fits together. Hopefully this information is useful for someone. If anything, I hope it helps future Aaron.
TL;DR: Browserify lets you use NodeJS-like requires in your code. If you want to use ES6 modules, you’ll need Babel/Babelify to convert your ES6 code into ES5, such that Browserify can understand it. Gulp is your friend in sequencing these tasks but there’s a couple of quirks due to the differences in libraries and output. Vinyl source and buffer help this.
Bunch of resources which helped me piece these things together (in rough order of usefulness for me)
Как заставить import работать в gulp
You can use ES6 import/export in Node.js by simply adding “type”: “module” to your package.json file, like this:
You can also save a file with the .mjs extension to be able to use import/export, for example:Advertisements
// abc.mjs
const abc = () => <
console.log(‘hello’)
>
export default abc;// index.js
import abc from ‘./abc.mjs’;
abc()
Какая у вас структура папок в gulp?
- 1 подписчик
- 14 окт.
- 109 просмотров
Как реализовать правильно структуру js файлов?
- 1 подписчик
- 12 окт.
- 60 просмотров
Как собрать БЭМ-проект с помощью Gulp?
- 1 подписчик
- 18 часов назад
- 21 просмотр
Using both “require” and “import” in the same file
What if you want to use both “require” and “import” in the same file? Is it possible? The answer is “Yes” but you have to do some extra things. Otherwise, you will get the following error:
ReferenceError: require is not defined in ES module scope, you can use import instead
To use “require” in the ES module scope, you have to define it. Just two lines of code to get the job done:
// These lines make “require” available
import < createRequire >from “module”;
const require = createRequire(import.meta.url);
Как сделать слежение над файлом SCSS в GULP?
- 1 подписчик
- 12 окт.
- 29 просмотров
Как интегрировать сборку фронтенда в django?
- 1 подписчик
- 05 окт.
- 45 просмотров
Как переключатся между html страницами, в gulp?
- 1 подписчик
- 26 сент.
- 43 просмотра
Почему не срабатывает gulp newer?
- 1 подписчик
- 25 сент.
- 40 просмотров
Как исправить ошибку TypeError: expected a string, в gulp?
- 1 подписчик
- 07 окт.
- 59 просмотров
Как настроить webpack через gulp?
- 1 подписчик
- 12 окт.
- 53 просмотра
Как оптимизировать GULP?
- 1 подписчик
- 22 сент.
- 56 просмотров
Вакансии с Хабр Карьеры
Программист баз данных MS-SQL ( удаленно)
LogistiX
•Москва
от 120 000 ₽
SberTech
•Санкт-Петербург
от 150 000 до 250 000 ₽
Инженер технической поддержки L2 (Infrastructure)
SberTech
•Москва
от 150 000 до 220 000 ₽
Ещё вакансии
Заказы с Хабр Фриланса
Создать страницу «Работа администратора с предложениями экспертов»
21 окт. 2022, в 11:59
1000 руб./за проект
Реализовать бэк на Laravel
21 окт. 2022, в 11:53
100000 руб./за проект
В мобильной версии “Каталог” заменить на бургер с выпадающим списком
21 окт. 2022, в 11:48
300 руб./за проект
Ещё заказы
Минуточку внимания
Присоединяйтесь к сообществу, чтобы узнавать новое и делиться знаниями
Самое интересное за 24 часа
Почему из-за плагина w3tc не открывается страница?
- 2 подписчика
- 0 ответов
Smartctl ругается на нечитаемые сектора, но MegaCli делает вид, что всё в порядке, кому верить?
- 2 подписчика
- 0 ответов
Какая погрешность в количестве фиксаций целевых событий в Яндекс метрике допустима?
- 2 подписчика
- 0 ответов
Почему в Chrome не отображается круг, а получается квадрат?
- 2 подписчика
- 1 ответ
Как умножить матрицы с помощью SSE?
- 3 подписчика
- 0 ответов
Как сделать аутентификацию по номеру телефона?
- 4 подписчика
- 0 ответов
Как подождать асинхронного выполнения всех подписчиков события?
- 3 подписчика
- 0 ответов
Ломается весь код в Sublime Text?
- 3 подписчика
- 1 ответ
Периодически падает сайт с ошибкой 502 как найти проблему?
- 3 подписчика
- 2 ответа
Какой компилятор выбрать для C++?
- 2 подписчика
- 3 ответа
- © Habr
- О сервисе
- Обратная связь
- Блог
A Complete Example
A good example that you cannot use “import” directly is with a JSON file. In this case, you can use “require” or read the content from the JSON file using the “fs” module. In this example, we will choose the first option.
The sample project we are going to build is really plain. Its job is to send data from a JSON file to the user after they make a GET request to http://localhost:3000 (with a web browser or Postman or whatever HTTP tool you like).Advertisements
1. Go to the folder you want your project to live in then install express by running:Advertisements
gulp sass, не работает @import
![]()
Вы можете опубликовать сообщение сейчас, а зарегистрироваться позже. Если у вас есть аккаунт, войдите в него для написания от своего имени.
Примечание: вашему сообщению потребуется утверждение модератора, прежде чем оно станет доступным.
Похожие публикации
![]()
![]()
Привет!
Недавно проходила первый этап на собесе с заданием и провалила. Нужно было создать копию отправленного изображения (прикреплено). Предполагаю, что ошибка была изначально в том, что требование «Use SASS variables by changing width and background, it has to change completely, the shape must be responsive (all its parts grow or shrink respectively)» не было выполнено. Фидбека не было, к сожалению. Работа проделана была только с html css. Но быть может были допущены другие другие ошибки? Буду признательна, если кто-нибудь укажет на них.
Код ниже и по ссылке: https://codepen.io/qizqepml-th. ls/LYeYqjX
Всем привет народ! Очень надеюсь на вашу помощь! Дело в том что я создавал сайты по видео урокам некого Михаила Базарова. Вот собственно его видео уроки https://camouf.ru/video/new_store/phpstorm.html?PAGEN_2=2
Теперь конкретно о проблеме: Дело в том, что данный человек использует bootstrap и sass. Он компилирует все стили в сжатый css. В этом то и проблема. У меня не компилируется, а стили на сайте не работают.
Что я сделал: установил Ruby, прописал в командной строке gem install sass, успешно установился. Перезагрузил компьютер и подключился к своему удаленному серверу через PhpStorm. Обмен между локальным и удаленным сервером идет успешно. Но на сайте не работают стили прописанные в sass
Скрин https://imgur.com/a/vV6QZBV
UPD: Оказалось что путь к файлам неверный, мог бы кто нибудь помочь настроить?