How do I change Javascript without restarting the server? - javascript

I can't seem to change any of my JavaScript files without restarting the server - it really kills a lot of the live-reloading fun of working in Phoenix. I don't do a ton of JavaScript, so I'm not sure if I'm doing something wrong.
Phoenix version: 1.2.0
Steps to reproduce:
Create a new project with mix phoenix.new foo
Create web/static/js/foo.js file.
In that file, write alert("Hello, world!");
In app.js, include import "web/static/js/foo" at the bottom.
Start Phoenix with mix phoenix.server and navigate to localhost:4000.
It doesn't matter how many times you refresh the page, you'll see an alert box with "Hello world!" every time, without fail.
Edit the foo.js message to be "Hello worlds!"
I expect that I'll still get an alert message with updated text, but the alert boxes stop appearing - altogether. They only start appearing again when I restart the server.
Is this intended behavior? A bug in Phoenix? Am I writing my JS code in a way that Brunch doesn't expect it? Is this a Babel issue? Should I be organizing my code differently?
Should add that I'm developing in Chrome on Linux - in case this might be a browser issue
Edit: I can't reproduce this exact issue anymore, but I'm still having issues with my non-toy project:
My original issue was in the app I'm actually developing - where I have global.jQuery = require("jquery") and global.bootstrap = require("bootstrap") in app.js. If I comment those two lines, save, and uncomment, I get a Javascript error in the browser: app.js:16Uncaught Error: Cannot find module 'jquery' from 'web/static/js/app.js'

Is this intended behavior? Yes.
A bug in Phoenix? No.
Am I writing my JS code in a way that Brunch doesn't expect it? Right you are.
Is this a Babel issue? Nope.
Should I be organizing my code differently? Probably.
Brunch (or Node.js or any other module bundler) expects relative path in import statement: it fails to resolve web/static/js/foo from web/static/js/app.js and does not mark foo.js as dependency of app.js (entry point). That is why it does not rebuild app.js when foo.js is changed. When Brunch is restarted, it completely rebuilds app.js, with latest foo.js (Brunch includes it because of joinTo.javascripts in config) version from the disk.
Specify relative paths (import "./foo") and prefer import jquery from ... over global.jquery = ...

Disable caching (if enabled) in your client (browser).
Disable caching (if enabled) in your server.

Related

Can't get CSS to load when I run npx webpack

I am working through the Odin Project and am stuck on the first lesson where we must build a webapp using webpack. I followed the tutorials here and hereon webpack's website, and I was able to get them to work. However, when I try to set up my own files to build my own project, I can't get CSS to load or a function in my index.js file.
I have the same directory style set up, and have even tried using the exact same index.js file they use in the tutorial.
I expect to get: a webpage to load that says "hello webpack" in red text.
Instead, I get this error: when I run $npx webpack, it says:
ERROR in ./src/style.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> .hello{
| color: red;
| }
# ./src/index.js 1:0-21
Upon googling the error, I found a stack overflow article and I tried renaming my rules array to 'loaders' in my .config file as this article suggests, but I still get the same error.
“You may need an appropriate loader to handle this file type” with Webpack and CSS
Also weird is the fact that some of the code in my index.js file works, and some does not. To elaborate, my console.log and alert works just fine after I run $npx webpack and load the page. However, they function that is supposed to add "hello webpack" to the DOM, does not, as evidence by the fact that nothing shows up at all. The page itself is blank.
My index.js code:
import './style.css';
console.log("console works");
alert("alert works");
function component() {
const element = document.createElement('div');
// Lodash, now imported by this script
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
element.classList.add('hello');
return element;
}
document.body.appendChild(component());
You will notice that it is nearly the exact same as the asset management index.js file from the webpack tutorial. I did this purposely to have as little variance as possible between my stuff and the tutorial.
I don't know if it is too much information, but a link to the whole repo as it currently is set up can be found here
Update:
I re-setup the file from the ground up and noticed that the CSS stopped working when I went out of my way to change the bundle.js link they had in their example to main.js. While I double-checked to make sure that I made the correct corresponding changes to output in my config file, making this change had the sum total outcome of not allowing my CSS to work for some reason.
What this reason is? I have no idea, and would be very interested to learn why this happened if someone has a suggestion
But on the offchance that one of my fellow Odin learners googles this problem, I kept the example's bundle.js instead of changing to main.js as my output script and it worked fine.
I'm going to update my github now so my original github link will likely be out of date going forward.
Going through your GitHub repo commit history, I see that at some point you named your Webpack configuration file weback.config.js instead of webpack.config.js (the p was missing). This was likely the source of the problem, as Webpack couldn't find a loader configuration for the .css file you're importing.

Webpack error, Loading chunk failed

Stack: Webpack 4.16.0, Node8, Vuejs2
I am seeing the below error, whilst serving my Vuejs application.
Error: Loading chunk 4 failed.
(missing: https://myapp.com/ui.chunk.bundle.js)
at HTMLScriptElement.s (demo:1)
This error is consistent across builds, the actual file itself is accesible via the URL.
I am using code splitting via import() and the initial app loads fine, but then the flow will break when another chunk is loaded, it can also vary between ui.chunk.bundle.js & vendors~ui.chunk.bundle.js.
When building for production, a new error is shown, but it seems related as also linked to loading modules:
demo:1 TypeError: Cannot read property 'call' of undefined
at o (demo:1)
at Object.349 (ui.chunk.bundle.js:1)
at o (demo:1)
at o.t (demo:1)
I have tried upgrading webpack and babel, but am at a loss as to what this could be down to as it was working perfectly fine before.
When running the application on my local machine and not Google App Engine, everything seems fine.
How the app is loaded:
It is loaded into other website via a script tag, so domainA.com runs the script tag which calls myapp.com/js and the flow begins, i.e the app loads various chunks based on some logic.
When accessing the webpack generated index page bundle at myapp.com everything loads correctly.
Please help!
That is rather deep and surely not easily fixed in two steps, best you create a new project using cli, if convenient with recommended presets, and if it still persist check the npm packages you installed and make sure none of them are discontinued and are up-to-date at least according to your version of vue.
Its might be due to "webpack.config.js" where you can just try with updating output object
module.exports = {
output: {
chunkFilename: '[id].chunk.[chunkhash].js',
}
};
Hope it should work!
This might be a cross site scripting problem.
Make sure that myapp.com sets the correct headers.
On myapp.com, set this header:
Access-Control-Allow-Origin: https://domainA.com
You should also make sure, that your script tag has async set to false:
<script async="false" …

WebPack sourcemaps confusing (duplicated files)

I decided to try out WebPack on a new project I'm spinning up today and I'm getting really strange behavior from the sourcemaps. I can't find anything about it in the documentation, nor can I find anyone else having this issue when skimming StackOverflow.
I'm currently looking at the HelloWorld app produced by Vue-CLI's WebPack template -- no changes have been made to the code, the build environment, or anything.
I installed everything and ran it like so:
vue init webpack test && cd test && npm install && npm run dev
Looking at my sourcemaps, I see the following:
This is a hot mess. Why are there three version of HelloWorld.vue and App.vue? Worse yet, each version has a slightly different version of the code and none of them match the original source. The HellowWorld.vue sitting in the root directory does match the original source, but what's it doing down there instead of in the ./src/components folder? Finally, why isn't there a fourth App.vue that has the original source for it?
As far as I can tell this may have something to do with the WebPack loaders. I've never gotten these kinds of issues with any other bundler, though. Below is an example of the exact same steps using the Browserify Vue-CLI template:
No webpack:// schema, only one copy of every file, the files actually contain the original source code (kind of important for source maps), no unexpected (webpack)/buildin or (webpack)-hot-middleware, no . subdirectory,.... just the source code.
I haven't worked with Vue so can't really describe how exactly this is happening but it seems to be related to Vue Loader. Looking at the documentation I did not really find anything that clarifies why it would create three different files for one component. But it does seem logical considering that a .vue file might contain three types of top-level language blocks: <template>, <script>, and <style>.
Also, looking at two of those files you do see a comment at end of each file that suggests it was modified in some way by a Vue loader. Either this
//////////////////
// WEBPACK FOOTER
// ./node_modules/vue-loader/lib/template-compiler
or
//////////////////
// WEBPACK FOOTER
// ./node_modules/vue-style-loader!./node_modules/css-loader
The third file is different but it still does have code that identifies it as being modified by Vue loader. Here is some of that code
function injectStyle (ssrContext) {
if (disposed) return
require("!!vue-style-loader...")
}
/* script */
import __vue_script__ from "!!babel-loader!../../node_modules/vue-loader/..."
/* template */
import __vue_template__ from "!!../../node_modules/vue-loader/..."
/* styles */
var __vue_styles__ = injectStyle
The document also says this:
vue-loader is a loader for Webpack that can transform Vue components written in the following format into a plain JavaScript module:
Which explains why you might not see the same type of behaviour with other bundlers.
Now, This might not be the answer you were looking for but just wanted to share what I had found.
This is actually a feature of webpack.
webpack has HMR (Hot Module Reloading). If you look in your network tab, go ahead and make an update to your HelloWorld.vue file. You'll see a js chunk come thru as well as an updated JSON manifest. Both of these will have a unique hash at the end for each time you make a change to the application. It does this so the browser does not have to do a full reload.
For a better explanation of this I would highly recommend reading through https://webpack.js.org/concepts/hot-module-replacement/

NodeJS 'Require' loading library in coffeescript, empty object in Javascript

I've come across an interesting problem in NodeJS that pops up now and then at work, and I haven't been able to figure it out.
I've written a back-end in CoffeeScript, which I then compile with grunt-contrib-coffee into Javascript in a ~/bin directory. I also include a library that I privately host on Bitbucket with the appropriate private keys, and install through npm. This library too is written in coffeescript.
Usually I'm able to include this library in Javascript without any headaches, using a simple require just like I would for any other library. However, occasionally one of the servers that's using the back-end gets updates, and it stops working. When I go check the error, it's always the same - 'require' passes, but instead of loading the actual library in JavaScript, it returns an empty object ({}). Running the code in coffeescript still works, but regardless of what I do - recompile, reinstall all dependencies, remove and clone the repository, the problem persists.
I've run out of ideas of what it might be myself, so I'm hoping that someone here has come across the problem before and might be able to point me in the right direction.
In the library package.json:
{
"name": "graph-engine",
"main": "./lib/graph"
}
In the library's graph.coffee
class Graph
constructor: () ->
# Perform init
module.exports = Graph
Then in the app's package.json:
{
"graph-engine": "git+ssh://git#bitbucket.org:<team>/graph-engine.git"
}
Finally, in the app itself:
GraphEngine = require "graph-engine"
engineInstance = new GraphEngine()
This works fine in coffeescript, but when compiling the app using grunt with the following setup for grunt-contrib-coffee:
coffee:
glob_to_multiple:
expand: true
flatten: false
cwd: 'src'
src: ['**/*.coffee']
dest: 'bin'
ext: '.js'
It fails to load the library correctly when running the compiled application, instead returning an empty object. Again, I'd like to emphasise that this does not always happen, and as such I didn't include any code or json files as I believed that it was unrelated.
Although the exact reason for the randomness of the behaviour eludes me to this day, I have found that it is related to these libraries being written in CoffeeScript.
It seems that depending on the load order, occasionally third party libraries would register coffee script and my own libraries would load correctly, whereas other times these libraries would load after my own libraries had loaded, resulting in an inability to load coffeescript. Therefore, the solution turned out to be fairly straightforward - register coffeescript. This can be done by putting the following at the start of the node.js app:
require('coffee-script/register')
Refer to the documentation for further information.

Getting a 404 error when deploying production build

I'm getting an error about Application.js not being found once I've copied the application over to a web server.
http://site/app/Application.js?_dc=1404504339794 404 (Not Found)
But obviously, this is wrong since once you run sencha app build everything is minified to app.js.
I looked at the generated app.js and index.html and there is no mention of Application.js anywhere.
I'm running: sencha app build production and copying the content of the production build over.
I am also getting a C1009: Circular reference warning during the build. And here it is:
in /controller/MainContent.js at line 192
var w = Ext.widget('EditPortalUserWindow'); //this creates a widget defined in the MainContent.js VIEW
And within that view at some point in one of the widgets, I use this to define the URL of a form:
url: GlobalVars.contactPostApiUrl //if I comment this out, the warning goes away...
GlobalVars is defined in app.js
Ext.define('GlobalVars', {
singleton: true,
contactPostApiUrl: 'http://site/CustomerPortal.WebAPI/api/contact/post'
});
I want GlobalVars to be available from everywhere, which is why I put it in app.js.
Any ideas ? Thank you!
I have seen something similar already - the production build requiring files it shouldn't. The following should help:
run the development version and see if you get any synchronous loading warning, fix if yes.
run sencha app build --clean
If it does not help run this sequence
sencha ant clean
sencha app refresh
sencha app build
#Francis Ducharme Adding to the above coversation , i m sending u two links which i guess might help u with C1009 .
C1009 Link 1
C1009 Link 2
I "solved" this issue by actually creating the file it is looking for (an empty one) and this seems to work. Although I feel a bit uncomfortable with this fix.

Categories