Cannot Get when running Webpack Config in React.js 2020 - javascript

I run 'watch' to execute webpack dev sever "watch": "webpack-dev-server --progress"
it compiles with no issues detected in terminal. However, when i go to http://localhost:8080 , I receive an error message 'Cannot Get'
I've created a sandbox.
What I've tried so far adding writeToDisk: true in webpack.config.js and including loaders for svg "file-loader" and css "css-loader" which corrected another error i was having regarding not using a loader for css. I've also tried changing the port to 3000. Not sure how relevant this is to solving this issue but i am using webstorm ide.
UPDATE:
I fixed this issue by moving index.html and manifest.json in to the src folder.
My question now is is there away to make this work without moving index.html and manifest into the same folder as webpack.config.js? If possible i'd rather leave index.html and manifest in the public folder.

I'd suggest reading through webpack's documentation on Output Management.
To your question:
My question now is is there away to make this work without moving index.html and manifest into the same folder as webpack.config.js?
You can make this work using the official HtmlWebpackPlugin to generate your index.html file. You'll be able to point it at your own file, wherever you want it, and it will also let you scale your code eventually to generate the html file from a template.
new HtmlWebpackPlugin({
template: 'path/to/index.html'
})

Related

How to make webpack-dev-server serve my index.html

I'm trying to get an extremely simple bare-bones TypeScript project setup with Webpack and I'm having an incredibly hard time for some reason.
I followed this guide and everything is working. When I simply run webpack my files will bundle and compile and be outputted into the dist directory. From there I can host them on a local server and it all works fine.
However, I want to avoid having to manually bundle and compile my code every single time I make a change, and I'd like for this to be done automatically each time I save my files. As far as I can tell this is a common use for Webpack and so I'm not sure why I'm having such an incredibly hard time finding any good information on it.
I decided to use the webpack dev server to accomplish this, so I read this tutorial and for the life of me I can't find anybody who explains how to get it to also server my index.html? When I run webpack serve --mode=development all goes well, and when I navigate to the localhost port that I server to I get a 404 error.
One of the "tips" on the previously linked page reads
If you're having trouble, navigating to the /webpack-dev-server route will show where files are served. For example, http://localhost:9000/webpack-dev-server.
When I navigate to localhost:1234/webpack-dev-server it tells me that it's only serving a single file: bundle.js Clearly a JavaScript file alone is not going to work, and I need it to also serve the index.html file that's in my dist directory.
Now, my knowledge here is very limited as this is my first time working with Webpack, but here's all the detail I can give and hopefully it's not accidentally totally unrelated:
Whenever my dev server reloads itself (whenever it's booted up or if a watched file changes while it's running) it only updates the bundle.js file that it's serving. It doesn't update the bundle.js file stored in my dist directory on my hard drive. How can I make it update both?
And also, how do I make the server also serve my index.html file instead of only the bundle.js? Where is it even getting that bundle.js from? Is it compiling all of my code from scratch to create that js file or is it taking that out of the dist directory?
And additionally, am I going about this totally in the wrong way? Where should my index.html even go? I put my TypeScript files into a src directory and they're converted to .js files and moved into my dist directory... Should I also put my index.html inside src or does it belong in dist or somewhere else entirely? When I put index.html in src it doesn't get copied over into dist, it just ignores it completely. If my index.html file doesn't belong in src it must belong in dist, but if it belongs in dist then how can I expect the dev server to find it and serve it along with the other TypeScript files in src? Why can't the dev server just serve everything in dist and automatically compile everything from src into dist? I must be misunderstanding the flow of it all, but I have no idea where to look for an explanation and I've been at this for several hours now.
Just a general explanation of how it all works would be very helpful as well, as I can't find a single article or forum post anywhere that details all the spaghetti going on with Webpack. I've been avoiding bundlers and all this NPM mess for as long as I can because I constantly run into issues like this, but I finally decided to jump in and just push through all the mess and I'm already regretting it. If someone could just point me (and other people having similar problems) to some good resources for learning about all the automagic going on that would be hugely appreciated. The Webpack documentation and guides are very much worthless to a newbie.
My Webpack config file:
const path = require("path");
module.exports = {
entry: "./src/index.ts",
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/,
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
devServer: {
compress: false,
static: false,
client: {
logging: "warn",
overlay: {
errors: true,
warnings: false
},
progress: true
},
port: 1234, host: "0.0.0.0"
}
};
Is your entry set in webpack? So that it is included?
entry: {
main: 'path/to/index.ts'
},
You could also try adding to your index.ts file
require('file-loader?name=[name].[ext]!../index.html');
Or
require("./src/index.html");
// Then In your webpack config file add a loader
loaders : { { test: /\.html/, loader: 'file?name=[name].[ext]' } }
Otherwise you could always copy this file over with webpack copy plugin
{
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
}
will need to run npm install --save-dev html-webpack-plugin to install it. As well as move your index.html file into your src folder
Please visit localhost:1234/bundle (Where bundle.js is your bundled file) the magichHTML route, which will load the HTML file with the bundled script.

Vue SPA - How to hide .vue files when rendered in browser

I'm working on a Single Page App developed in Vue.js hosted on a node.js server.
At the moment it is still under development but eventually it will be exposed to external customers, and since we will deal with sensitive data we would like to avoid to have the .vue files and the relative file-tree structure visible when users inspect the element in devtool.
See attached screenshot as a sample that shows the files I would like to hide.
Is there a way to achieve that?
I was able to make webpack export the SPA in a bundle by playing around with the config file.
In the file ./config/index.js I have changed the following flags:
build: {
// other code...
devtool: '', // Previously it was set as '#source-map'
productionSourceMap: false, // Previously it was set as true
cssSourceMap: false, // Previously set as true
// other code...
}
I've found the solution by reading the webpack documentation where it explains what the settings do: https://webpack.js.org/configuration/devtool/#production
Thanks everyone for putting me in the right direction.
It seems you are running on development mode of vue. And Of course files will be visible by then. When shipping a Vue SPA, it should be build and compiled into chunks of JS.
You can build a production version of your spa by running.
npm run build
This will produce 1 folder and 1 file inside the dist
--dist
----static
----index.html
When this were served. No .vue files will be visible anymore.
And when you check it on Browsers Dev tools. It should look more like of this
The folders node_modules, src, and theme should be a level up in the folder structure. Therefore, you have to modify your paths pointing to those files.
The app.js can be in that folder only with files that are JS executables.

How to put Vue.js in production mode using webpack 2.7?

I've got an existing code base in which Vue.js has performance problems. I also see this notice in the browser console:
so I guess an easy fix could be to put Vue into production mode.
In the suggested link I try to follow the instructions for webpack. We're on Webpack version 2.7 (current stable version is 4.20). In the instructions it says that in Webpack 3 and earlier, you’ll need to use DefinePlugin:
var webpack = require('webpack')
module.exports = {
// ...
plugins: [
// ...
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
}
So in my package.json I've got a build script defined:
To build for production I run yarn run build and it runs a build.js file (paste here) which in turn calls webpack.base.conf.js (paste here) and webpack.prod.conf.js (paste here).
As you can see in the paste I use the DefinePlugin as suggested by the docs.
I also found a file called vue-loader.conf.js (paste here) and to be sure I also added the DefinePlugin in there as well.
I can run yarn run build which ends without errors, but when serve the site over Apache and open the browser it still shows the notification that we're in development mode.
To be sure it actually uses the files created by webpack I completely removed the folder /public/webpack/ and checked that the webinterface didn't load correctly without the missing files and then built again to see if it loaded correctly after the command finished. So it does actually use the files built by this webpack process. But Vue is actually not created in production mode.
What am I doing wrong here?
The problem may be in your 'webpack.base.conf.js' as i suspected, thank you for sharing it, upon searching i've found an issue resolving your 'production not being detected' problem on github here
The solution requires that you change 'vue$': 'vue/dist/vue' to 'vue$': vue/dist/vue.min in production.
You will find the original answer as:
#ozee31 This alias 'vue$': 'vue/dist/vue' cause the problem, use vue/dist/vue.min in production environment.

webpack javascript in one line

I am running an Angular 4 project with Webpack 2.4.
For some reason, some of the third party Javascript plugins files are being modified after compilation, and they are shown in the browser's debugger as a very long, one line string:
This is very inconvenient because I can't use Chrome / FF debugger, as I am unable to set up any breakpoint in there.
Following some of the already posted questions in this site and many others, I extracted the webpack.config.js file by executing ng eject
The section where the js files are imported look as follows:
{
...
"scripts": [
...
"script-loader!./node_modules/handsontable-pro/dist/handsontable.full.js",
...
],
"styles": [
...
]
},
"output": {
"path": path.join(process.cwd(), "dist"),
"filename": "[name].bundle.js",
"chunkFilename": "[id].chunk.js"
}
The file handsontable.full.js does not look like that in my project's folder. It seems to be pretty structured. It seems to suffer some kind of modification when the application is built and served.
More puzzling, many other files in the node_modules folder do not have the same problem.
Now, I tried to tweak the webpack.config.js, as suggested in many forums, specifically SourceMapDevToolPlugin, but with very little luck.
So, several questions arise here:
What is happening here? The transformed file doesn't seem to be a minified file, or a hashed file... What is it?
How can I prevent this from happening, so I can set up breakpoints in that file and use the browser's debugger for tracing, var inspect, etc.
Check the devtool: property in the Webpack config object. If it's set to eval, cheap-eval-source-map (or something like it, don't remember all the eval options), try changing it to source-map or cheap-source-map.
Full list of options here: https://webpack.js.org/configuration/devtool/

Is there a way I can change any of the files shown here to deploy with webpack?

What's coming? (1) Short background. (2) Question. (3) Detail (short; file listings just long enough to show relevant information). (4) Question again.
Short background: I want to deploy my web site using webpack. webpack is looking for style-loader and css-loader in the wrong directories, so my builds aren't completing.
Question
Is there a way I can change any of the files shown here to deploy with webpack?
Detail
environment
Windows 10 Home -64, up-to-date/ Toshiba Satellite with AMD A6
Node v6.2.0/ webpack v1.13.2
relevant files and directory structure
C:\Dev\example\example.js
C:\Dev\example\bluebird.js
C:\Dev\example\jquery.js
C:\Dev\example\img\image1.jpg
C:\Dev\example\img\image2.jpg
C:\Dev\example\img\svg1.svg
C:\Dev\example\built\package.json
C:\Dev\example\built\webpack.config.js
C:\Dev\example\built\index1.html
C:\Dev\example\built\index2.html
C:\Dev\example\built\example.bundle.js
C:\Dev\example\built\[hash1].jpg
C:\Dev\example\built\[hash2].jpg
C:\Dev\example\built\[hash3].svg
C:\Dev\node-modules\webpack
C:\Dev\node-modules\css-loader
C:\Dev\node-modules\file-loader
C:\Dev\node-modules\html-loader
C:\Dev\node-modules\style-loader
C:\Dev\node-modules\uglify-js
C:\Dev\node-modules\url-loader
C:\Dev\example\built\package.json
{
"name": "example",
"version": "0.0.1",
"description": "example",
"main": "example.bundle.js",
"author": "Bald Eagle"
}
call to webpack: I call webpack at the command prompt from C:\Dev\example\built with one line (two here for your convenience)
node C:\Dev\node_modules\webpack\bin\webpack.js -p --display-reasons
--display-error-details --display-modules --profile
C:\Dev\example\built\webpack.config.js
"use strict"
let path = require("path")
let webpack = require("webpack")
let preferEntry = true // for OccurrenceOrderPlugin
module.exports = {
context: "C:/Dev/example/built",
entry: [
"./index1.html",
"./../jquery.js",
"./../bluebird.js",
"./../example.css"
],
output: {
path: "C:/Dev/example/built",
filename: "./example.bundle.js",
publicPath: "http://www.example.com"
},
module: {
loaders: [
{
test: /\.(?:gif|jpg|jpeg|svg)$/,
loader: "file!url"
},
{
test: /\.html$/,
loader: "html"
},
{
test: /\.png$/,
loader: "url-loader?mimetype=image/png"
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
} ],
plugins: [
new webpack.optimize.UglifyJsPlugin({minimize: true}),
new webpack.ProvidePlugin({
'window.jQuery': 'jquery',
'window.$': 'jquery',
}) ] },
resolve: {
root: path.resolve("./index1.html"),
modulesDirectories: ["node_modules", "built"],
fallback: "C:/Dev"
},
resolveLoader: {
fallback: "C:/Dev",
modulesDirectories: ["node_modules"]
}
}
C:\Dev\example\built\index1.html: My goal for this HTML file is to point webpack the right direction to collect all information for the web site into its example.bundle.js file. I shortened one long line (clip) and excluded irrelevant lines, including the entire body.
<!doctype html>
<html>
<head>
<script src="./../example.js"></script>
<link href="./../example.css" rel="stylesheet" type="text/css" />
<link href="https://fonts.googleapis.com/css? (clip) type="text/css" />
<script src="./../jquery.js"></script>
<script src="./../bluebird.js"></script>
</head>
<body>
</body>
</html>
feedback from webpack
It outputs routine information about building pieces of example.bundle.js (represented with ...), except these: (I added any double asterisks **; I broke some long lines and indented the later parts of such lines.)
...
[9] ./../example.css 919 bytes {0} [built] [**2 errors**]
single entry ./../example.css [0] multi main
WARNING in ./example.bundle.js from UglifyJs
...
Condition always false [C:/Dev/~/style-loader!
C:/Dev/~/css-loader!**./../example.css:10,0**]
Dropping unreachable code [C:/Dev/~/style-loader!
C:/Dev/~/css-loader!**./../example.css:12,0**]
Side effects in initialization of unused variable update
[C:/Dev/~/style-loader!C:/Dev/~/css-loader!
**./../example.css:7,0**]
**ERROR** in ./../example.css
Module not found: Error: Cannot resolve 'file' or 'directory'
./../node_modules/css-loader/index.js in
C:/Dev/example/built\..
resolve file
**C:/Dev/example/built\node_modules\css-loader\index.js
doesn't exist**
[plus more similarly inaccurate variants; it should be looking
for C:\Dev\node_modules\css-loader\index.js; it's there]
...
**ERROR** in ./../example.css
Module not found: Error: Cannot resolve 'file' or 'directory'
./../node_modules/style-loader/addStyles.js in
C:/Dev/example/built\..
resolve file
**C:/Dev/example/built\node_modules\style-loader\addStyles.js.webpack.js
doesn't exist**
[plus more similarly inaccurate variants]
...
With the double asterisks, I wanted to highlight that webpack outputted that there'd be two errors and outputted the two errors. Also, I wanted to highlight the cited points of error in css. Those lines are below.
C:\Dev\example\example.css: I show only the first twelve lines because of the lines webpack cited as errors; I added line numbers.
1 /* example web site
2 * blah
3 * blah
4 * blah
5 * blah
6 * blah
7 *
8 * Version
9 */
10
11 /* defaults */
12 body, div {
My conclusion: The points webpack cited are not points of error. Maybe the points cited apply to a minified version of the file. Or to some code.
Problem when I point a browser to index1.html above: All content and rendering are fine; JavaScript isn't enabled. (Consistent with not processing css correctly?)
C:\Dev\example\built\index2.html: My goal for this HTML file is to use the same webpack techniques I'll use in the index.html that will be on the web server. I changed this the same ways I changed index1.html.
<!doctype html>
<html>
<head>
<script src="./example.bundle.js"></script>
<link href="https://fonts.googleapis.com/css? (clip) type="text/css" />
</head>
<body>
</body>
</html>
Problem when I point a browser to index2.html immediately above: All content shows (including the three images), but (1) JavaScript isn't enabled and (2) there's no effect from css (no colors or positioning, etc.) (Consistent with not processing css correctly?)
Question
Is there a way I can change any of the files shown here to deploy with webpack?
Thanks for taking the time to read. Thanks in advance for any responses.
Need more detail? I'll provide it if I can.
It seems like you've set up your project in a very unusual style for Node.js development which makes your setup more complicated than it needs to be. I'm not sure if that is a hard requirement, but since you've not mentioned it to be required, I'm assuming you are allowed to change your directory structure.
Use local dependencies
In Node.js, all dependencies are installed separately for each project. It enables you to use different versions of a dependency while working on different projects without the need to switch these dependencies manually. You should put the package.json in the root folder of your project (I assume C:\Dev\example in your case) and then run npm install webpack css-loader style-loader --save-dev. NPM is the package manager for Node.js that comes pre-bundled with the executable so it should already be installed on your system. After running npm install you should see a node_modules folder which contains all these project-specific dependencies. You should not commit these dependencies to your version control system because they may contain platform-specific binaries that are not usable on different machines. Every developer in this project needs to run npm install first.
Configure your common commands under scripts
NPM provides the possibility to add common commands as scripts to your package.json. This way, other developers (including "Future You") only need to remember npm run some-script instead of all the command-line options. One little known feature of NPM is, that it prepends ./node_modules/.bin to your $PATH on runtime which means that inside scripts you can reference any executable installed in your local node_modules just as if it was installed globally. Thus you only need to write:
"scripts": {
"start": "webpack --config ./path/to/webpack.config.js"
}
and it will use your local webpack installation. As a side-note: It's best-practice to provide a "start" script. It can be called by just running npm start.
Your webpack config
Your webpack config looks ok, but I have some advice:
You should separate between your development stuff and the actual build. Usually, the webpack.config.js is placed in the root of your project because then you just need to run webpack and webpack will look for a config in the current directory. Then, you should have a src or app folder which contains all the development files, including the index HTML files as you've mentioned. At last, you create a build folder which is completely wiped before a build. This way, your build does not contain any obsolete files.
Do not use absolute paths in your webpack.config. It makes sharing your project a lot harder – including "Future You" that moves the project to another directory. Use the Node.js builtin path module and the special module variable __dirname to resolve absolute paths. You can also use require.resolve to use Node's resolving algorithm.
Do not set the context and the publicPath option unless you know what you are doing. Given from the information you've provided, I doubt that these options are necessary here.
Since you've installed all the dependencies locally, you should remove all the resolving options because it should work out-of-the-box now.
Although it is permitted, you should not omit the -loader postfix in your loader configurations. It can lead to hard-to-understand errors when you have a css or html module in your node_modules just by coincidence.
The problem with index.html files
webpack is a JavaScript bundler. That's why you need to have a css- or an html-loader if you want to include HTML or CSS. These loaders transform HTML or CSS into a JavaScript module by transforming the text contents into strings that are exported. This has some nice advantages like hot module replacement or CSS modules. But it also means that you can't use an HTML or CSS file as the only entry point to your website. Every HTML and CSS will eventually be translated to JavaScript. This trade-off is ok for single-page applications where you need JS anyway, but it is probably surprising for everyone who tries to use webpack on a static site.
Since you're not the first one with this problem, several solutions have already emerged. My recommendation is to use the HTML Webpack Plugin in combination with the Extract Text Webpack Plugin.
The Extract Text Webpack Plugin can be used to extract static JS strings out of the bundle into a speparate file. This is exactly what you need to remove CSS from the JS bundle.
The HTML Webpack Plugin creates an index HTML file that includes all the generated JS and CSS files. Out of the box, it will just generate an HTML file with no contents (often referred to application shell which is typical for single-page applications). Since you already have content in your index HTML files, you need to configure your HTML files as templates. You'll need to add a plugin for each HTML file.
These plugins work pretty well, but this setup is already pretty complex. You should decide if you want to use webpack just for JS or also for HTML and CSS.

Categories