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.
Related
I'm using webpack 4.26.1 (latest).
The code import('./images/header.csv') produce the following error:
Uncaught (in promise) Error: Cannot find module './images/header.csv'
at webpackMissingModule (home.js:9)
My project structure:
'project-dir/src/components/home.js' (im here)
'project-dir/src/components/images/header.csv'
I tried to read https://webpack.js.org/api/module-methods/ but failed to understand what to do except adding random webpack comments which I don't understand.
Also, from the docs, I may be found the source of the problem but I'm not exactly sure I understand it and how to solve it.
Fully dynamic statements, such as import(foo), will fail because webpack requires at least some file location information. This is because foo could potentially be any path to any file in your system or project. The import() must contain at least some information about where the module is located, so bundling can be limited to a specific directory or set of files.
Every module that could potentially be requested on an import() call is included. For example, import(./locale/${language}.json) will cause every .json file in the ./locale directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file like english.json or german.json will be available for consumption. Using the webpackInclude and webpackExclude options allows us to add regex patterns that reduce the files that webpack will bundle for this import.
More than providing me a solution, I will appreciate any answer that covers what is the actual problem with my code.
Thank you.
I have pretty strange problem with webpack and aurelia.
I've made new webpack configuration based on the internet and in official webpack and aurelia documentation. Compilation works, everything seems to be fine. But in runtime, I'm getting this error:
css-resource.js?ada4:17 Uncaught (in promise) Error: Failed loading required CSS file: aurelia-notify/style.css
at fixupCSSUrls (css-resource.js?ada4:17)
at eval (css-resource.js?ada4:56)
at <anonymous>
Originally, I thought it might be some issue related to this comment:
// CSS required in templates cannot be extracted safely
// because Aurelia would try to require it again in runtime
mentioned here: https://github.com/aurelia/skeleton-navigation/blob/master/skeleton-typescript-webpack/webpack.config.js#L70 but it doesn't seem to be.
While creating working example, I made a strange discovery. Everything works, until I load one of CSS files from following dependencies:
<require from="aurelia-bootstrap-datetimepicker/src/bootstrap-datetimepicker-bs4.css"></require>
<require from="eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css"></require>
(Please not the dependencies and error message - they are completely unrelated).
Here is example repository: https://github.com/klinki/aurelia-webpack-issue
(also have a look at tag working-state: https://github.com/klinki/aurelia-webpack-issue/tree/working-state - only one commit back and it works).
I fixed your problem:
new ModuleDependenciesPlugin({
'aurelia-testing': [ './compile-spy', './view-spy' ],
// 'aurelia-notify': [ './style.css' ]
}),
First this is not needed because AureliaPlugin installs a loader by default on all HTML files to detect and process <require> dependencies. style.css is required from an HTML template somewhere inside aurelia-notify. This is handled for you, no config required.
Second this was bad because the rest of your config is set up with appropriate loaders based on whether the CSS dependency comes from inside a .html (assuming an Aurelia <require>) or not (assuming a JS import).
By using ModuleDependenciesPlugin in this way, Webpack did not see a .html origin for the dependency and incorrect loaders were applied.
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 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.
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"))