Accessing Rails with webpacker - ruby-on-rails

I'm trying to implement what is described here on my Rails 6.1 app (with webpacker).
"dependencies": {
"#rails/ujs": "^6.1.3",
"#rails/webpacker": "5.4.3",
...
}
My packs/application.js looks like
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
// require("channels")
document.addEventListener("turbolinks:load", () => {
const remoteLinks = Array.from(document.querySelectorAll("a[data-remote='true']"))
remoteLinks.forEach(function(element) {
element.dataset.url = element.href
element.href = "javascript:void(0);"
})
Rails.href = function(element) {
return element.dataset.url || element.href
}
})
And I get Uncaught ReferenceError: Rails is not defined.
What am I missing here?
UPDATE
I was missing
import Rails from "#rails/ujs"

Related

Using ActionText without webpack

I try to implement ActionTest with old way asset pipeline (without Webpack) on rails 6
Almost all is good, except loading of #rails/actiontext
in my application.js I've
//= require trix
//= require #rails/actiontext
The riche editor appear, I can change bold/italic text, but can't add image (not uploaded)
I've an JS error : Uncaught SyntaxError: Cannot use import statement outside a module
on line : import { AttachmentUpload } from "./attachment_upload" from attachment_uplaod.js in actiontext.
Any way to achieve this without webpack?
thanks
I don't know what will be the official way, but I did it this way as I'm waiting for an updated install generator:
Prerequisites
hotwire-rails
CSS
Copy the CSS file in your asset pipeline (https://github.com/basecamp/trix/tree/main/dist)
JS Libraries
In app/assets/javascripts/libraries create these two files
Updated content may be found on https://www.skypack.dev
// app/assets/javascripts/libraries/actiontext#6.1.4.js
export * from 'https://cdn.skypack.dev/pin/#rails/actiontext#v6.1.4-znF92tREya92yxvegJvq/mode=imports/optimized/#rails/actiontext.js';
export { default } from 'https://cdn.skypack.dev/pin/#rails/actiontext#v6.1.4-znF92tREya92yxvegJvq/mode=imports,min/optimized/#rails/actiontext.js';
// app/assets/javascripts/libraries/trix#1.3.1.js
export * from 'https://cdn.skypack.dev/pin/trix#v1.3.1-EGGvto9zyvcAYsikgQxN/mode=imports/optimized/trix.js';
export { default } from 'https://cdn.skypack.dev/pin/trix#v1.3.1-EGGvto9zyvcAYsikgQxN/mode=imports,min/optimized/trix.js';
Import through Stimulus
In app/assets/javascripts/controllers create this file
//app/assets/javascripts/controllers/trix_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
connect() {
import("actiontext").catch(err => null)
import("trix").catch(err => null)
}
}
On pages where trix/action_text should be loaded, add a data-controller="trix" to the relevant div
And voilĂ  !
https://github.com/rails/rails/issues/41221#issuecomment-871853505
Got Action Text working by copying the actiontext scripts into a custom file, and removing the imports and exports.
And second, you will need to require activestorage in your application.js to make use of DirectUpload.
application.js
//= require trix
//=# require #rails/actiontext
//= require activestorage
//= require actiontext
actiontext.js
// Copied from node_modules/#rails/actiontext/app/javascript/actiontext/attachment_upload.js
class AttachmentUpload {
constructor(attachment, element) {
this.attachment = attachment;
this.element = element;
// Requires `require activestorage` in application.js
this.directUpload = new ActiveStorage.DirectUpload(
attachment.file,
this.directUploadUrl,
this
);
}
start() {
this.directUpload.create(this.directUploadDidComplete.bind(this));
}
directUploadWillStoreFileWithXHR(xhr) {
xhr.upload.addEventListener("progress", event => {
const progress = (event.loaded / event.total) * 100;
this.attachment.setUploadProgress(progress);
});
}
directUploadDidComplete(error, attributes) {
if (error) {
throw new Error(`Direct upload failed: ${error}`);
}
this.attachment.setAttributes({
sgid: attributes.attachable_sgid,
url: this.createBlobUrl(attributes.signed_id, attributes.filename)
});
}
createBlobUrl(signedId, filename) {
return this.blobUrlTemplate
.replace(":signed_id", signedId)
.replace(":filename", encodeURIComponent(filename));
}
get directUploadUrl() {
return this.element.dataset.directUploadUrl;
}
get blobUrlTemplate() {
return this.element.dataset.blobUrlTemplate;
}
}
// Copied from node_modules/#rails/actiontext/app/javascript/actiontext/index.js
addEventListener("trix-attachment-add", event => {
const { attachment, target } = event;
if (attachment.file) {
const upload = new AttachmentUpload(attachment, target);
upload.start();
}
});
This still uses ES6 syntax, so if you want to support older browsers and aren't using Babel, you might want to rewrite or transpile this to ES5.

Rails Webpacker - How to access objects defined in webpack entry file from views [HTML file]

I have a Rails 6 application and using Webpacker for assets.
I have the following code in file app/javascript/packs/application.js :
export var Greeter = {
hello: function() {
console.log('hello');
}
}
And I have the following script in one of my view (HTML) file:
<script>
$(document).ready(function(){
Greeter.hello();
});
</script>
Note: I am using JQuery and it is working fine.
I am getting the following error:
Uncaught ReferenceError: Greeter is not defined.
How can we use libraryTarget and library to expose the bundled modules, so that it can be accessed from HTML files as well ?
Or, is there any other way of doing it using Rails Webpacker ?
Any help would be much appreciated!
To do this without directly mutating the window object in your application code, you'll want to export Greeter as a named export from your application.js pack and extend the Webpack config output to designate the library name and target var (or window will also work).
// config/webpack/environment.js
environment.config.merge({
output: {
library: ['Packs', '[name]'], // exports to "Packs.application" from application pack
libraryTarget: 'var',
}
})
// app/javascript/packs/application.js
export {
Greeter
}
<script>
$(document).ready(function(){
Packs.application.Greeter.hello();
});
</script>
The library name is arbitrary. Using the [name] placeholder is optional but allows you to export to separate modules if you're using multiple "packs".
As I cannot comment rossta's answer, here is what I had to do. My default config was:
// config/webpack/environment.js
const { environment } = require('#rails/webpacker')
module.exports = environment
and I just had to add the additionnal config in it:
// config/webpack/environment.js
const { environment } = require('#rails/webpacker')
environment.config.merge({
output: {
library: ['Packs', '[name]'], // exports to "Packs.application" from application pack
libraryTarget: 'var',
}
})
module.exports = environment
After that, as mentioned by rossta, each symbol which is exported in app/javascript/packs/application.js can be accessed from the DOM as Packs.application.<symbol>.
in app/javascript/packs/application.js:
import Greeter from '../greeter.js'
Greeter.hello()
and in app/javascript/greeter.js:
export default {
hello : function(){
console.log('hello')
}
}
I could fix the issue exposing Greeter object to window as follows:
export var Greeter = {
hello: function() {
console.log('hello');
}
}
window.Greeter = Greeter;
However, I am still looking for a Webpack way of accomplishing this.

Rails 6 + yarn + datatables issue

I bumped into troubles with webpacker. I'm using Rails 6.beta3 and trying to add Datatables to my app. My steps:
yarn add datatables.net-dt
then in app/javascript/packs/application.js:
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require("channels")
import 'bootstrap/dist/js/bootstrap';
import 'popper.js/dist/popper.js';
require( 'datatables.net-dt' )();
config/webpack/environment.js:
const { environment } = require('#rails/webpacker')
const webpack = require('webpack')
module.exports = environment
environment.plugins.append('Provide', new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
}))
After this if load a page I get an error in js console:
Uncaught TypeError: Cannot set property '$' of undefined
at DataTable (jquery.dataTables.js:129)
jquery.dataTables.js:
var DataTable = function DataTable(options) {
this.$ = function (sSelector, oOpts) { // <---------error is here. Turns out this is not defined variable
return this.api(true).$(sSelector, oOpts);
};
Any ideas? Thanks in advance
Opps. Its my bad. I found the issue. At the end of app/javascript/packs/application.js there was an error. I thought it didn't make impact on overall performance, but after eliminating of this things started working properly.
my app.js
// that code so it'll be compiled.
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require("channels")
import 'bootstrap/dist/js/bootstrap';
require('select2');
import 'popper.js/dist/popper.js';
require("chart.js");
require("leaflet");
import $ from 'jquery';
window.jQuery = $;
window.$ = $;
// var dt = require( 'datatables.net-dt' );
// var dt = require( 'datatables.net-bs4' )( window, window.$ );
require('datatables.net-bs4');
var moment = require('moment');
window.moment = moment
require('bootstrap-daterangepicker');
var feather = require('feather-icons/dist/feather.js')
function onready() {
feather.replace()
console.log('onready')
}
$(document).on('ready turbolinks:load', onready);
/* globals Chart:false, feather:false */
(function () {
feather.replace()
}())
My app/javascript/packs/application.js
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require("channels")
import 'bootstrap/dist/js/bootstrap';
import 'popper.js/dist/popper.js';
My application.js
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require("channels")
import 'bootstrap/dist/js/bootstrap';
import 'popper.js/dist/popper.js';
require( 'datatables.net-dt' )();
And the result is
jquery.dataTables.js:129 Uncaught TypeError: Cannot set property '$' of undefined
at DataTable (jquery.dataTables.js:129)
at Module../app/javascript/packs/application.js (application.js:38)
at __webpack_require__ (bootstrap:19)
at bootstrap:83
at bootstrap:83
The odd thing is the bootstrap part of the stack!

Load fonts from node_modules in react-rails application with webpack

I have a react-rails application set up with webpacker.
I am trying to load font-awesome-pro with it's fonts from node_modules.
I assume this is a trivial task but I can't seem to find any good documentation on how to do this.
This is what I have so far:
package.json dependencies:
"dependencies": {
"#rails/webpacker": "3.5",
"babel-preset-react": "^6.24.1",
"bootstrap": "^4.1.3",
"prop-types": "^15.6.2",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-slick": "^0.23.1",
"react_ujs": "^2.4.4",
"slick-carousel": "^1.8.1",
"tachyons-z-index": "^1.0.9"
},
"devDependencies": {
"#fortawesome/fontawesome-pro": "^5.2.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.7.0",
"file-loader": "^2.0.0",
"path": "^0.12.7",
"webpack-dev-server": "2.11.2"
}
file.js:
var path = require('path');
module.exports = {
test: /\.(woff(2)?|eot|otf|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
exclude: path.resolve(__dirname, '../../app/assets'),
use: {
loader: 'file-loader',
options: {
outputPath: 'fonts/',
useRelativePath: false
}
}
}
environment.js
const { environment } = require('#rails/webpacker')
const file = require('./file')
environment.loaders.prepend('file', file)
module.exports = environment
application.scss:
#import '#fortawesome/fontawesome-pro/scss/fontawesome.scss';
application.rb:
config.assets.paths << Rails.root.join('node_modules')
What am I missing? From what I can gather, webpack should be looking at the node_modules directory, finding font files based on the webpack test and putting the assets into the output directory: fonts/.
FontAwesome with webfonts:
For me with the free version the example below is working well. I don't know the pro version, but if I'm not mistaken, you just have to rename fontawesome-free to fontawesome-pro in the paths.
application.scss:
$fa-font-path: "~#fortawesome/fontawesome-free/webfonts";
#import "~#fortawesome/fontawesome-free/scss/fontawesome.scss";
#import "~#fortawesome/fontawesome-free/scss/solid.scss";
#import "~#fortawesome/fontawesome-free/scss/regular.scss";
#import "~#fortawesome/fontawesome-free/scss/brands.scss";
In SCSS ~ (tilde import) means that look for the nearest node_modules directory. Not all SASS compilers supports it, but node-sass does, and this is the common for Webpack.
This way in your html you only have to use your application.css. There's no need to include any other FontAwesome css files.
Your font loader config seems OK (tested, worked). With that Webpack should resolve the font files and then copy them to your desired output as you wanted. This needs that your css-loader be configured with url: true but I that is the default.
A minimal/usual config for the loaders in your Webpack config file:
module: {
rules: [
{
test: /\.s?css$/,
use: [
MiniCssExtractPlugin.loader, // optional (the most common way to export css)
"css-loader", // its url option must be true, but that is the default
"sass-loader"
]
},
{
// find these extensions in our css, copy the files to the outputPath,
// and rewrite the url() in our css to point them to the new (copied) location
test: /\.(woff(2)?|eot|otf|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: {
loader: 'file-loader',
options: {
outputPath: 'fonts/'
}
}
}
]
},
Loading only the needed fonts (the new way with JS and SVGs)
Again, I will demonstrate it with the free version because I don't have the pro version.
This way your generated bundle will only contain those icons what you need, resulting in a much smaller size which means faster page loads. (I'm using this in my projects)
The needed packages:
#fortawesome/fontawesome-svg-core
#fortawesome/free-brands-svg-icons
#fortawesome/free-regular-svg-icons
#fortawesome/free-solid-svg-icons
Include this in your scss file:
#import "~#fortawesome/fontawesome-svg-core/styles";
Create a new file, name it fontawesome.js:
import { library, dom, config } from '#fortawesome/fontawesome-svg-core';
config.autoAddCss = false;
config.keepOriginalSource = false;
config.autoReplaceSvg = true;
config.observeMutations = true;
// this is the 100% working way (deep imports)
import { faUser } from '#fortawesome/free-solid-svg-icons/faUser';
import { faHome } from '#fortawesome/free-solid-svg-icons/faHome';
import { faFacebook } from '#fortawesome/free-brands-svg-icons/faFacebook';
import { faYoutube } from '#fortawesome/free-brands-svg-icons/faYoutube';
// this is the treeshaking way (better, but read about it below)
import { faUser, faHome } from '#fortawesome/free-solid-svg-icons';
import { faFacebook, faYoutube } from '#fortawesome/free-brands-svg-icons';
library.add(faUser, faHome, faFacebook, faYoutube);
dom.watch();
.. and then require it somewhere in your js:
require('./fontawesome');
That's all. If you want to read more on this, start with understanding SVG JavaScript Core, have a look on its configuration and read the documantation of treeshaking.

Module parse failed: Unexpected character '#' when using React on Rails with Antd.

I'm using React on Rails and have been trying to use Antd UI framework.
I have successully imported components from 'antd' like buttons and Datepickers
import { Button } from 'antd';
but they are not styled at all. Looking at my server I have the following error...
ERROR in ./node_modules/antd/lib/button/style/index.less
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #import "../../style/themes/default";
| #import "../../style/mixins/index";
| #import "./mixin";
# ./node_modules/antd/lib/button/style/index.js 5:0-23
# ./app/javascript/packs/application.js
ERROR in ./node_modules/antd/lib/style/index.less
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| #import "./themes/default";
| #import "./core/index";
|
I have tried a few different ways to access the styles like directly references the specific stylesheet in my jsx file
//app/javascript/bundles/Page/components/Page.jsx
import React, { Component } from "react";
// import { Button, DatePicker } from 'antd'
import { Button } from 'antd';
// import Button from 'antd/lib/button';
// import 'antd/lib/button/style/css';
export default class Page extends Component {
render() {
return (
<div >
<Button type="primary">Primary</Button>
<Button>Default</Button>
<Button type="dashed">Dashed</Button>
<Button type="danger">Danger</Button>
</div>
);
}
}
Looking at the Antd docs, I have followed the Importing on demand technique and added
"import", {
"libraryName": "antd",
"style": "css",
}
]
to my .babelrc file
https://ant.design/docs/react/getting-started#Import-on-Demand
I have also tried to install the less and less-loader as I'm pretty sure it has something to do with a css file containing an '#' which indicates to me that it is a less or sass file.
The only successful way I've been able to load the styles is by putting
#import 'antd/dist/antd.css';
in my app/assets/stylesheets/page.scss.
While this option works, it does not allow for the ability to import on demand and feels like the incorrect way to import the css as it uses the rails asset pipeline instead of webpack ( via webpacker)
For me the issue was that I needed to have differently configured .less loaders in webpack for both the .less files found in antd's modules & the .less files I had written locally in my project.
For Antd I have this (Note that it's excluding /src/):
{
test: /\.(less)$/,
exclude: [
/\.(css)$/,
/src/
],
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader"
},
{
loader: "less-loader",
options: {
javascriptEnabled: true,
modifyVars: get_theme()
}
}
]
},
And for my own .less files I have this:
{
test: /\.(less)$/,
exclude: [
/\.(css)$/,
/node_modules/
],
use: [{
loader: 'style-loader' // creates style nodes from JS strings
}, {
loader: 'css-loader' // translates CSS into CommonJS
}, {
loader: "less-loader",
options: {
javascriptEnabled: true
}
}]
},
Versions of dependencies for this that I was using:
"css-loader": "^3.3.2",
"less": "3.10.3",
"less-loader": "^5.0.0",
"mini-css-extract-plugin": "^0.8.0",
"style-loader": "^1.2.1",
"antd": "4.4.2",
"webpack": "^4.43.0",

Resources