Using the bundle feature of mvc4 courses
Uncaught SyntaxError: Unexpected token <
on loading. With debug="true" everything is works like excepted.
How can i solve the error or can i disable the bundle feature just for scripts?
Solved
Renamed the bundle name to not match up with any directory
Before you can answer the question of what caused this error, you must first figure out where the error occurred. The only difference in the syntax of your code when bundled is that it is minified. A very simple way to do this is to use a Bundle instead of a ScriptBundle:
var thirdParty = new Bundle("~/bundles/thirdParty").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/bootstrap.js",
"~/Scripts/jquery-ui-{version}.js",
"~/Scripts/jquery.mockjson.js",
"~/Scripts/jQuery.XDomainRequest.js",
"~/Scripts/knockout-{version}.js"
);
thirdParty.Transforms.Clear();
bundles.Add(thirdParty);
Now, if you have multiple JavaScript bundles, do this for them one by one until you have the culprit bundle.
The only way that I've found to debug these issues is to take your bundle and split it in half to break it down further:
var thirdParty1 = new Bundle("~/bundles/thirdParty1").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/bootstrap.js",
"~/Scripts/jquery-ui-{version}.js"
);
bundles.Add(thirdParty1);
var thirdParty2 = new ScriptBundle("~/bundles/thirdParty2").Include(
"~/Scripts/jquery.mockjson.js",
"~/Scripts/jQuery.XDomainRequest.js",
"~/Scripts/knockout-{version}.js"
);
bundles.Add(thirdParty2);
Notice that we've only disabled minification for one of the two bundles - thirdParty1. Be sure and update your #Scripts.Render to point to your new bundles. When you build and reload, you will either continue to get the error, or you won't, and will then know which half contains the troublesome code. But be sure and test it both ways, minifying thirdParty1 and unminifying thirdParty2 in my example and vice-versa to be certain something else isn't going on. You also might want to keep DevTools or whatever browser debugger you have open and look at the source of your bundles to ensure they are acting as expected.
Continue by moving the scripts from the minified bundle (thirdParty1 in my case) from the unminified bundle (thirdParty2) either one at a time or in chunks, if you have a lot of scripts. Remember to rebuild in-between, and be careful not to change the inclusion order of your scripts.
That should at least get you down to the file that has the issue - and hopefully searching for "<" will get you your answer.
Hope that helps.
His solution helped me, renaming the bundle to be different than the directory. I was grouping mine like so:
#Styles.Render("~/jqueryui")
#Scripts.Render("~/jqueryui")
There seems to be a bug when doing it this way with jquery UI styles. I just renamed the bundle to:
#Styles.Render("~/jqueryuiz")
#Scripts.Render("~/jqueryui")
and this fixed it for me. So the scripts don't seem to be affected in this way, nor do similar bundles, I have about 20 sets of bundles loaded and this is the only one causing issues.
My issue:
I reference script files in my Content folder but have a bundle name of ~Scipts. I renamed my bundle to ~DefaultScripts and that fix my issue. I didn't want to reference the Scripts folder, but it was going there instead of my Content folder.
bundles.Add(New ScriptBundle("~/Scripts").Include(
"~/Content/assets/global/plugins/jquery.min.js",
"~/Content/assets/global/plugins/bootstrap/js/bootstrap.min.js",
"~/Content/assets/global/plugins/js.cookie.min.js",
"~/Content/assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js",
"~/Content/assets/global/plugins/jquery.blockui.min.js",
"~/Content/assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js",
"~/Content/assets/global/scripts/app.js",
"~/Content/assets/layouts/layout2/scripts/layout.min.js",
"~/Scripts/custom.js"))
bundles.Add(New ScriptBundle("~/DefaultScripts").Include(
"~/Content/assets/global/plugins/jquery.min.js",
"~/Content/assets/global/plugins/bootstrap/js/bootstrap.min.js",
"~/Content/assets/global/plugins/js.cookie.min.js",
"~/Content/assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js",
"~/Content/assets/global/plugins/jquery.blockui.min.js",
"~/Content/assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js",
"~/Content/assets/global/scripts/app.js",
"~/Content/assets/layouts/layout2/scripts/layout.min.js",
"~/Scripts/custom.js"))
Related
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.
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/
I have a js file with a require call which is too dynamic for Webpack to be analyzed. The file is from a dependency and there's no replacement for it (and I need that code in the bundle).
The error:
Cannot statically analyse 'require(..., ...)' in line 1822
How can I tell webpack "If file X fails, don't bother and continue"?
An improvement on that can be "If file X fails because it can't be statically analyzed, don't bother and continue".
I'm analyzing writing a plugin that can remove that piece of code and after compilation add it again (I will have requirejs loaded to resolve those requests), but it doesn't seem very easy, so I wanted to check if there's a simpler solution first.
Any pointers on how that plugin should look like would be appreciated too : )
Thanks!
In my Angular JS app, I'm using a lot of third party packages, mainly maintained via Bower.
When I use Grunt to concatenate all of them into one mega file, I'm getting errors when I load my page, for example that
Uncaught ReferenceError: angular is not defined and
GET http://localhost:8080/theproj/v4/dist/app/bootstrap.css.map 404 (Not Found)
What is the best way to properly concatenate all these files to ensure that everything loads in the right order and doesn't cause problems?
First issue: A lot of times third party libraries must be loaded in a particular order. That looks like like it's the source of your first issue. Something is trying to use angular and it's getting loaded before the angular code. You should refactor your grunt task to use a pre-defined order for third party libraries.
Second issue: You probably are missing the .map file. This is a file used by Chrome dev tools to show you the original source for the css (sass or less). Either provide the map file, or delete the reference to it from bootstrap.css. Or just ignore the error, it's only an error when you have chrome dev tools open, and doesn't actually affect your application.
For the issue of the correct order for your javascript files, i had that problem in a larger project where noone really had a clue which was the correct order.
Luckily we found that the Google Closure Compiler does exactly this: https://github.com/google/closure-compiler
You give it all your js files and it analyzes them all and concatenates them in order
$ java -jar compiler.jar --js_output_file=out.js in1.js in2.js in3.js ...
There is even a grunt plugin for the connection: https://github.com/gmarty/grunt-closure-compiler
'closure-compiler': {
frontend: {
closurePath: '/src/to/closure-compiler',
js: 'static/src/frontend.js',
jsOutputFile: 'static/js/frontend.min.js',
maxBuffer: 500,
options: {
compilation_level: 'ADVANCED_OPTIMIZATIONS',
language_in: 'ECMASCRIPT5_STRICT'
}
}
},
Another way would be to change your javascripts into AMD or CommonJS modules, this way you don't have to worry about the correct order. RequireJS (http://requirejs.org/docs/start.html) is a possibility for AMD for example or Webpack (http://webpack.github.io/) ...or many many others.
My situation is as follows:
My project based on RequireJS.
I am using RequireJS Optimizer for to create a single JS file.
Some of the module use a certain third party library as a dependency.
The third party is NOT included in the optimized file (libName: empty
in the build config).
RequireJS is configured through var require = {} object which appears
on EACH PAGE, right above the RequireJS. The object defines a path to
the unminifed version of the library, among other things.
What i'd like to achieve:
Use the same config file in both development and production (the require={} object is included with tag on each page). During development I'd like modules to use the UNMINIFIED version of the third party.However, after optimization occurs, i would like all the modules to use the minified version of that third party.
I did think of a solution in theory, but it seems a bit messy and Im hopeful cleaner solution exists:
To have the runtime config point to unminified version
var require = {
paths:{
'thirdParty':'lib/thirdParty'
}
}
Create a module which execute (lets call it "PathRewrite" Module):
requirejs.config({
paths:{
'thirdParty':'lib/thirdParty.min'
}
})
In runtime configuration, define path to "PathRewrite" as empty
var require = {
paths:{
'thirdParty':'lib/thirdParty',
'PathRewrite':'empty'
}
}
In the build configuration file define a real Path to "PathRewrite" in order for it to be included in the "main" file (concatenated file after build).
Include "PathRewrite" as a dependency of a module which is executed first.
What I hope that will happen is that during dev, when optimized file is not used, PathRewrite is will not be used, hence the path to unminified third party in the runtime config will be used.
When the project is optimized, PathRewrite will be included and executed. According to RequireJS documentation, it is possible to run RequireJS configuration twice and the configuration will be appended/overwritten. PathRewrite execution will overwrite the path to "thirdParty" to minified, which will thus be used by all the modules.
Hopefully i've provided enough information. I'd be glad hear of other ways to get this done. Thanks in advance.
This topic appears to have been explored a bit in this answer:
Loading min.js files Generated by TypeScript with Require
Don't let the title discourage you. Typescript is not the core issue of the question being answered there. Unfortunately, the discussion reveals that the RequireJS optimizer may be the only way to get decent minification to work, as it seems incapable of selecting alternate paths properly.
Why don't you want to use inbuilt RequireJs optimizer? You may just include this option
optimize : "uglify2"
and all your and third-party code will be minified after concatenation. In this case you don't need to use minified versions of third-party libraries.