webpack 2, angular 2 - using "require" with path built using variable - javascript

my issue is this:
whenever I'm using the following syntax inside angular ->
let myCmp = 'test1';
let cmp = require('./components/'+myCmp+'/bootstrapCmp.component.ts');
I'm getting all the components that inside the components folder within my final bundle, not just 'test1';
(I'm using the angular 2 WebPack starter pack of the AngularClass team -
https://github.com/AngularClass/angular-starter
Had anyone this issue too?
the component I'm loading / so is all other ones are basic angular 2 components.
thanks in advance, I'm struggling with it for too much ^^

hope the solution i found for myself will help other developers :
in the webpack.common.js file i've added new file to my entry object which i called : boot.js .
so the structure is like this :
entry: {
main:['./src/polyfills.browser.ts','./src/assets/boot.ts','./src/main.browser.ts']
}
the boot.ts file, contains an object with all the relavent components that i will be using (references).
while the bunlder (wepback) is running, whenever i need some component i'm going to this object i've created inside the boot.ts file, the final bundle file contains now only the components i want.

Related

Webpack loader for file, subfiles and add them to tracking list

I have the map+tilemap project created in a 3rd-party app. The whole project is a set of files, the main file (XML) representing the 2D game level map and some other files (subfiles) representing graphics and tilemaps.
I am trying to create a Webpack Loader that will compile and convert the whole map/tilemap project into JSON object, that is comfortable to use in javascript. And I still can't get how to:
How can I access subfiles (taken from relative paths from the main file), what is the way to access the current directory (where the main file is placed), and the name of the main file?
How can I explain to Webpack to track changes in all subfiles, so it will run the loader again automatically to compile the whole map/tilemap project (partial re-packing).
I spent 2 days to find any working solutions, it is possible at all?
Thanks a lot!
For the first question, webpack loader is expose the file info by this, you can do like this:
module.exports = function (source) {
const loaderContext = this;
const { sourceMap, rootContext, resourcePath } = loaderContext;
const sourceRoot = path.dirname(path.relative(context, resourcePath));
...
}
For the second question, i think that maybe you can use the module.hot to track the subfiles change, like this:
if (module.hot) {
module.hot.accept('filepath', ()=>{
...
})
}

Rails 6 Webpacker calling javascript function from Rails view

I have following structure for Javascript in my Rails 6 app using Webpacker.
app/javascript
+ packs
- application.js
+ custom
- hello.js
Below shown is the content in the above mentioned JS files
app/javascript/custom/hello.js
export function greet(name) {
console.log("Hello, " + name);
}
app/javascript/packs/application.js
require("#rails/ujs").start()
require("jquery")
require("bootstrap")
import greet from '../custom/hello'
config/webpack/environment.js
const { environment } = require('#rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
})
)
module.exports = environment
Now in my Rails view I am trying to use the imported function greet like shown below
app/views/welcome/index.html.haml
- name = 'Jignesh'
:javascript
var name = "#{name}"
greet(name)
When I load the view I am seeing ReferenceError: greet is not defined error in browser's console.
I tried to search for a solution to this problem and found many resources on web but none turned out to help me. At last when I was drafting this question in the suggestions I found How to execute custom javascript functions in Rails 6 which indeed is close to my need however the solution shows a workaround but I am looking for a proper solution for the need because I have many views which needs to pass data from Rails view to JS functions to be moved custom files under app/javascript/custom folder.
Also I would highly appreciate if anybody can help me understand the cause behind the ReferenceError I am encountering.
Note:
I am not well-versed in Javascript development in Node realm and also new to Webpacker, Webpack, Javascript's modules, import, export, require syntax etc so please bear with me if you find anything silly in what I am asking. I have landed up in above situation while trying to upgrade an existing Rails app to use version 6.
Webpack does not make modules available to the global scope by default. That said, there are a few ways for you to pass information from Ruby to JavaScript outside of an AJAX request:
window.greet = function() { ... } and calling the function from the view as you have suggested is an option. I don't like have to code side effects in a lot of places so it's my least favorite.
You could look at using expose-loader. This would mean customizing your webpack config to "expose" selected functions from selected modules to the global scope. It could work well for a handful of cases but would get tedious for many use cases.
Export selected functions from your entrypoint(s) and configure webpack to package your bundle as a library. This is my favorite approach if you prefer to call global functions from the view. I've written about this approach specifically for Webpacker on my blog.
// app/javascript/packs/application.js
export * from '../myGlobalFunctions'
// config/webpack/environment.js
environment.config.merge({
output: {
// Makes exports from entry packs available to global scope, e.g.
// Packs.application.myFunction
library: ['Packs', '[name]'],
libraryTarget: 'var'
},
})
// app/views/welcome/index.html.haml
:javascript
Packs.application.greet("#{name}")
Take a different approach altogether and attach Ruby variables to a global object in your controller, such as with the gon gem. Assuming you setup the gem per the instructions, the gon object would be available both as Ruby object which you can mutate server-side and in your JavaScript code as a global variable to read from. You might need to come up with some other way to selectively call the greet function, such as with a DOM query for a particular selector that's only rendered on the given page or for a given url.
# welcome_controller.rb
def index
gon.name = 'My name'
end
// app/javascript/someInitializer.js
window.addEventListener('DOMContentLoaded', function() {
if (window.location.match(/posts/)) {
greet(window.gon.name)
}
})
#rossta Thanks a lot for your elaborate answer. It definitely should be hihghly helpful to the viewers of this post.
Your 1st suggestion I found while searching for solution to my problem and I did referenced it in my question. Like you I also don't like it because it is sort of a workaround.
Your 2nd and 3rd suggestions, honestly speaking went top of my head perhaps because I am novice to the concepts of Webpack.
Your 4th approach sounds more practical to me and as a matter of fact, after posting my question yesterday, along similar lines I tried out something and which did worked. I am sharing the solution below for reference
app/javascript/custom/hello.js
function greet(name) {
console.log("Hello, " + name)
}
export { greet }
app/javascript/packs/application.js
require("#rails/ujs").start()
require("bootstrap")
Note that in above file I removed require("jquery"). That's because it has already been made globally available in /config/webpack/environment.js through ProvidePlugin (please refer the code in my question). Thus requiring them in this file is not needed. I found this out while going through
"Option 4: Adding Javascript to environment.js" in http://blog.blackninjadojo.com/ruby/rails/2019/03/01/webpack-webpacker-and-modules-oh-my-how-to-add-javascript-to-ruby-on-rails.html
app/views/welcome/index.html.haml
- first_name = 'Jignesh'
- last_name = 'Gohel'
= hidden_field_tag('name', nil, "data": { firstName: first_name, lastName: last_name }.to_json)
Note: The idea for "data" attribute got from https://github.com/rails/webpacker/blob/master/docs/props.md
app/javascript/custom/welcome_page.js
import { greet } from './hello'
function nameField() {
return $('#name')
}
function greetUser() {
var nameData = nameField().attr('data')
//console.log(nameData)
//console.log(typeof(nameData))
var nameJson = $.parseJSON(nameData)
var name = nameJson.firstName + nameJson.lastName
greet(name)
}
export { greetUser }
app/javascript/packs/welcome.js
import { greetUser } from '../custom/welcome_page'
greetUser()
Note: The idea for a separate pack I found while going through https://blog.capsens.eu/how-to-write-javascript-in-rails-6-webpacker-yarn-and-sprockets-cdf990387463
under section "Do not try to use Webpack as you would use Sprockets!" (quoting the paragraph for quick view)
So how would you make a button trigger a JS action? From a pack, you add a behavior to an HTML element. You can do that using vanilla JS, JQuery, StimulusJS, you name it.
Also the information in https://prathamesh.tech/2019/09/24/mastering-packs-in-webpacker/ helped in guiding me to solve my problem.
Then updated app/views/welcome/index.html.haml by adding following at the bottom
= javascript_pack_tag("welcome")
Finally reloaded the page and the webpacker compiled all the packs and I could see the greeting in console with the name in the view.
I hope this helps someone having a similar need like mine.

Webpack 4 bundles or ignores dynamic imports

I'm using dynamic imports in index.js:
import('./componentA');
import('./componentB');
import('./componentC');
const myIndexVar = 'My Index Var';
index.ts is the entry point in my webpack.config.js.
The result is a single bundle containing all 4 files - index and the 3 components.
My goal is to have each of the files separately in my dist folder, so that index can load the components dynamically on demand at runtime.
i.e. at runtime I'd like to load index.js, and in turn it'll request components a-c via dynamic imports when needed.
Depending on events yields the same results:
document.body.onclick = () => import('./componentA');
If I try something like this it completely ignores the component and doesn't add it in any way to the dist folder:
let componentName = './componentA';
import(componentName);
I tried following this article:
https://webpack.js.org/guides/code-splitting/
Am I misunderstanding what's supposed to happen?
If I'm not on the right track, is there any alternative that can help me reach my goal?

How to use plain js lib in a ts angular 2 app

I'm building an Angular 2 (rc.4) app with TypeScript and I would like to use D3.
I've installed D3 through npm install, but this is a js module without .d.ts file. However, I've found a .d.ts file here.
What I do now (a component):
import d3 from 'node_modules/d3/build/d3.min.js';
//<reference path="../declaration/d3.d.ts" />
//[...]
export class Test {
constructor() {
this.object = this.d3.select(...);
}
}
If I set a break-point on that line in the TS file, I can execute everything just fine. However, the mapped .js version of this file was converted to:
var d3_min_js_1 = require('node_modules/d3/build/d3.min.js');
[...]
this.object = d3_min_js_1.default.select(...);
The d3_min_js_1 object exists, but there is no 'default', so it throws a undefined exception...
How can I get this mapping right (I'm pretty sure d3.d.ts does nothing) or how can a use the plain javascript in the TS-file (without it getting f*cked up by the compiler)?
I hope this plunker will help you: https://embed.plnkr.co/qM3qrk3swvalQFBh1Db1/

How to include a vue component only when required in spa?

I have made components and saved into different '.vue' files and compiling them with the help of elixir / gulp and of course browserify.
I am including all the components into one js file,
I want to know that how to reduce the size of "build.js" file that is called each time in every page that contains all the components of the app.
It would be helpful to know such a way to include components only when they required.
This question is not related to Vue-router
I am new to vue.js
Here is your answer: http://router.vuejs.org/en/lazy.html
This is supported natively in Webpack. The example is:
require(['./MyComponent.vue'], function (MyComponent) {
// code here runs after MyComponent.vue is asynchronously loaded.
})
If you want to do it with Broswerify, you'll need https://github.com/substack/browserify-handbook/blob/master/readme.markdown#partition-bundle . The code looks like:
router.map({
'/async': {
component: function (resolve) {
loadjs(['./MyComponent.vue'], resolve)
}
}
})

Categories