Webpack, new chunk is loading in with wrong path - javascript

I am trying to chunk my app - attempting to follow webpacks guide on how-to (https://webpack.github.io/docs/code-splitting.html). So I have a seperate chunk set up for my app, I can see that webpack is generating 1.bundle.js in my build folder, however it is pasting it onto my index.html with an incorrect path, and in my console I see the fetch error for the 1.bundle.js file.
So my webpack config looks like so (im just using the webpack:dev for now):
return {
dev: {
entry: {
index: './client/app.jsx'
},
output: {
path: path.join(__dirname, '..', '..', 'dist', 'client'),
publicPath: "/dist/client/",
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}, {
test: /\.json$/,
loader: 'json-loader'
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
resolveLoader: {
fallback: [path.join(__dirname, 'node_modules')]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": JSON.stringify("dev")
}
})
]
},
and in my index.html I manually add <script src="bundle.js"></script> and that has been working great. It looks like when this builds now, webpack is applying its own script tag on my index like so
<script type="text/javascript" charset="utf-8" async="" src="/dist/client/1.bundle.js"></script>
However this path is incorrect, it should just be src="1.bundle.js". I have tried tweaking the path and publicPath but nothing seems to work. Is there a way to have webpack add the correct path? Thanks!

You should change publicPath for this snippet:
publicPath: "/"
It will always serve your chunks from root path.

Even though it is answered and accepted, I am providing additional helpful info for others with similar problems.
There are two different purposes for which the 2 parameters are used.
Output:path : The directory the bundle files mentioned in entry section are saved into. For example, the bundle.js for the 'entry' entry you had mentioned. In this case, it will be saved in webconfigfolder+"../../dist/client" folder.
Output: publicPath: The directory prefix that is added to refer to a module when accessed from browser. 0.bundle.js is an unnamed chunk created by code splitting. It will be placed in the output:path mentioned above but will be referred in your html using the public path.
So,if your files as in this case is stored in /dist/client folder, but the index.htm is served in /dist/client, you should give the public path as ./. If htm is served from /dist, the public path should be given as ./client/.
The public path is useful for chunks created for async loading which are called from browser dynamically.

This is because you have given reference to publicPath. So it will try to load the script from this publicPath though the file is not present there.
Removing publicPath can resolve the error

Related

how can I bundle multiple libraries with webpack and use them in a browser

Webpack describes a multi-main entry feature that seems to do exactly this, it bundles several libs into one file. The problem is that when I load that file only the last library on the list is available.
I've created a small demo on github.
There are 2 libraries each exporting a single symbol, only lib2.d2 is accessible from the test.html that loads the bundled JS. If you look in the bundle file you can see the code from lib1 but it's not exported in any way that I can find.
The webpack config is below. I suspect the problem is that there's no way to supply 2 library names when there's out only output and so the last one over-writes the earlier ones.
const path = require('path');
module.exports = {
entry: ['./js/lib1.js', './js/lib2.js'],
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
library: {
name: 'MyLibrary',
type: 'umd',
},
filename: 'lib.js',
path: path.resolve(__dirname, 'dist'),
},
"optimization": {
"minimize": false,
usedExports: true,
},
mode: "development",
};
If you're curious why I would want to do this, I'm doing some development on wix.com. The only way to push JS files up to their server is copy/paste one at a time. Bundling a bunch of stuff into one file will save me some pain. My current work-around is to output to multiple files and then cat them all together with something export const exportLib1 = lib1 for each one. That gives me a JS file that I can import and access each one but there must be an easier way.

React import images from public folder

I'm trying to get static images fro my public directory but is not being found. I'm not using CRA, so maybe is some configuration with Webpack that I'm missing. Using file-loader module and importing the image works on Dev Mode, but doesn't work in for my production server specification
My Project structure:
\public
\static
\images
image.png
\src
\component
component.js
...
package.json
webpack.common.js
webpack.dev.js
webpack.prod.js
On component.js, I want to get image.jpg on static/images folder like this:
<img src='/static/images/image.png'></img>
But I'm getting a 404 not found.
My webpack.commom.js:
const CleanWebPackPlugin = require('clean-webpack-plugin')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = {
entry: {
main: './src/index.js'
},
output: {
filename: '[name].[hash].js',
path: path.resolve('./dist'),
publicPath: "/"
},
module:{
rules:[
{
test: /\.js$/,
exclude: ['/node_modules'],
use: [{ loader: 'babel-loader'}],
},
{
test: /\.s?(a|c)ss$/,
use: [{
loader: 'style-loader'
}, {
loader: 'css-loader'
},{
loader: 'sass-loader'
}]
},
{
test: /\.(png|jpe?g|gif)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: 'index.html'
}),
new CleanWebPackPlugin(),
],
}
And the Dev version:
module.exports = merge(common, {
mode: 'development',
devServer: {
host: 'localhost',
port: 3000,
open: true,
historyApiFallback: true,
publicPath: "/",
}
})
Thank you in advance.
I assume you want to display such image more than once. In that case, is annoying to keep writing something like '%PUBLIC_URL%/img/static/images/image.png' or {process.env.PUBLIC_URL + '/img/static/images/image.png'} two, three or more times within your jsx code. Basically, without a plugin is imposible to import images from the public folder if your app is rooted in the src folder. However I did find a solution for me and was quite simple in fact. It was something like this:
import React from 'react'
var path = process.env.PUBLIC_URL;
var image = "/img/static/images/image.png";
and then, within jsx code:
<img src={path + image}/>
it worked for me, hope this is helpful for anyone! :D
You are using file-loader as webpack plugin, which does not work in the way of "just mirroring the directory structure of public to dist". You can find the documentation for that plugin here: https://webpack.js.org/loaders/file-loader/
Basically, what the plugin does is, if you import an image file (actually programatically importing it, not just using a string reference to its path), the file is copied to your dist directory, potentially renamed and than in your compiled source code the proper file name is inserted.
So in your case, if you want to solve your problem using file-loader, you would reference the image file like
// Relative path to image file from js file
import imageFile from './assets/image.png';
// ...
const component = props => <img src={imageFile}></img>;
If you want to use the approach of actually just mirroring a public-directory to the dist directory, you need to use an additional webpack-plugin for that (e.g. https://stackoverflow.com/a/33374807/2692307)
By the way, I assume it works in dev-mode because you are setting '/' as public path, so the development server just serves everything in the root directory as well. That is something different than copying the files to dist however as you are trying to achieve.
Not sure if this help but I'm will give it a try
Try to add public path to your dist folder also something like this
output: {
path: path.resolve(__dirname, "/dist"),
filename: "[name].js",
publicPath: "/dist/"
},

Webpack - How to bundle/require all files of a folder (subfolder)

I am trying to see if there is a shorter way of running webpack bundles, and also why my loaders do not work.
Here is my code:
module.exports = {
context: path.join(__dirname, 'dist'),
entry: ['./ES6bundle.js', './jQuery.js'],
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist')
}
};
// module: {
// loaders: [{
// test: /\.js?$/,
// exclude: /node_modules/,
// loader: 'babel-loader',
// query: {
// presets: ['env']
// }
// }]
// };
The module.exports works but when I run the loaders I get errors.
My other question is about consolidating multiple entries into one file.
The project I am working on has many JS files, and I was wondering if there was a shortcut for multiple entries. Instead of typing out multiple entries' filenames, can I grab all JS files in the same folder or have a JS file to require them all?
Let me know if this makes sense or not. I am relatively new to programming. Thanks!
Regarding the second part of your question:
can I grab all JS files in the same folder or have a JS file to
require them all
You can have one entry file and in there you do:
module.exports = {
context: path.join(__dirname, 'dist'),
entry: ['./jQuery.js', './allJsFilesOfFolder.js'],
allJsFilesOfFolder.js:
require.context("../scripts/", true, /\.js$/);
This will bundle all scripts inside scripts and all its subfolders.
You need to install #types/webpack-env to have context at your hand.
Specify false if you want to bundle only the scripts in the scripts folder.
You can do the same with other resources like images, you only have to adapt the regex
Copy #Legends comment as answer here.
have no experience with vue files, but as I said you can bundle not only js files, but also image files, for example the regex for image files would be: /.(png|ico|svg|jpg|gif)$/.

vueJS + webpack: importing fonts, CSS, and node_modules

I'm starting with Vue.js and Webpack and I'm having some doubts about how to correctly import and reference my fonts, CSS, and node_modules correctly.
I started my application using vue-cli, and here's the resultant structure:
build
config
node_modules
src
--assets
--components
--router
static
And here's my webpack.base.conf file:
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src')
}
},
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}
First of all, where is the correct place to put my custom CSS and images? I'm currently putting them inside assets/css and assets/img, respectively (I created these folders). Is it correct?
I also have some CSS and fonts from external libraries (Bootstrap and Font Awesome, for example) that I have installed via NPM. They're located at node_modules.
If I'm not wrong, Webpack transforms, and copies these files to another location. How can I reference them on my Vue files and CSS files?
Using import './assets/css/style.css'import '../node_modules/path/to/bootstrap.min.css' works (at least in production), but should I be using another path?
Inside my custom CSS files, I reference some fonts from an external library using:
src: url('/node_modules/roboto-fontface/fonts/Roboto/Roboto-LightItalic.eot')
The code compiles, but when I open the page in the browser, I receive a 404 error when searching for these fonts. How should I be referencing these fonts in my custom CSS?
First of all, where is the correct place to put my custom css and images? I'm currently putting them inside assets/css and assets/img, respectively (I created these folders). Is it correct?
This is kind of a subjective question, but the short answer is yes.
The cli tool already created this for you, defined some stuff in the Webpack config files, so why not use it?
Using import './assets/css/style.css'import '../node_modules/path/to/bootstrap.min.css' works (at least in production), but should I be using another path?
Webpack embeds the css into the it's JS file, so if you don't import it Webpack will not know about it.
Here is an example with loading images dynamically
<ul id="albums">
<li v-for="album in albums">
<img :src="LoadImage(album.data.imagefile)" />
</li>
</ul>
if you'll just hand the src binding the artwork file it will fail to load it, so we hand the image file name to a method that goes like this
LoadImage(filename) {
const image = require('#/assets/img/' + filename)
return image
}
now inside the method we load the image from the assets folder ( using the # notation that was configured in the webpack.base.conf file under resolve.alias )
So yes, using the import/require functions are the way to go for Webpack to get to know your files.
Inside my custom css files, I reference some fonts from an external library using:
src: url('/node_modules/roboto-fontface/fonts/Roboto/Roboto-LightItalic.eot')
The code compiles, but when I open the page in the browser, I recieve a 404 Error when searching for these fonts. How should I be referencing these fonts on my custom css?
It's best that you'll copy everything you want in your dist folder in your src folder. I'm not really sure, never tried it, but looking at the webpack.prod.conf file it looks like it will only copy files from the src/assets folder.
Regarding the font not loading, this is a bit different since the url-loader will handle the files, so you have to think of it from the browser point of view, and reference it like a url path.
here is an something i have in one of my components
#font-face {
font-family: BebasNeue;
src: url('./assets/fonts/BebasNeue.otf');
}
See how i didn't used the # notation to reference it from the src folder? no need for urls.
I'm guessing you already answered this question and if not, Hope that helps!
You can ask questions here http://chat.vuejs.org/ and get answers from the community and the core team.
Quck solution
what i did comment #font-face {} section and build and added custom css to style file

webpack loaders and include

I'm new to webpack and I'm trying to understand loaders as well as its properties such as test, loader, include etc.
Here is a sample snippet of webpack.config.js that I found in google.
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
include: [
path.resolve(__dirname, 'index.js'),
path.resolve(__dirname, 'config.js'),
path.resolve(__dirname, 'lib'),
path.resolve(__dirname, 'app'),
path.resolve(__dirname, 'src')
],
exclude: [
path.resolve(__dirname, 'test', 'test.build.js')
],
cacheDirectory: true,
query: {
presets: ['es2015']
}
},
]
}
Am I right that test: /.js$/ will be used only for files with extension .js?
The loader: 'babel-loader', is the loader we install using npm
The include: I have many questions on this. Am I right that anything we put inside the array will be transpiled? That means, index.js, config.js, and all *.js files in lib, app and src will be transpiled.
More questions on the include: When files get transpiled, do the *.js files get concatenated into one big file?
I think exclude is self explanatory. It will not get transpiled.
What does query: { presets: ['es2015'] } do?
In webpack config there are multiple things for configuration, important ones are
entry - can be an array or an object defining the entry point for the asset you want to bundle, can be a js as test here says do it only for /.js$. Your application if has multiple entry points use an array.
include - defines the set of path or files where the imported files will be transformed by the loader.
exclude is self explanatory (do not transform file from these places).
output - the final bundle you want to create. if you specify for example
output: {
filename: "[name].bundle.js",
vendor: "react"
}
Then your application js files will be bundled as main.bundle.js and react in a vendor.js files. It is an error if you do not use both in html page.
Hope it helped
This documentation helped me understand better. Looks like it is for webpack 1 but still applies.
https://webpack.github.io/docs/configuration.html#module-loaders
Loaders
An array of automatically applied loaders.
Each item can have these properties:
test: A condition that must be met
exclude: A condition that must not be met
include: An array of paths or files where the imported files will be transformed by the loader
loader: A string of “!” separated loaders
loaders: An array of loaders as string
This example helped me understand what is going on. Looks like you use either include or exclude but not both. The test is a condition applied to all files. So if you include a folder, each file must pass the test condition. I have not verified this, but based on the example provided by the documentation, it look like that is how it works.
module: {
rules: [
{
// "test" is commonly used to match the file extension
test: /\.jsx$/,
// "include" is commonly used to match the directories
include: [
path.resolve(__dirname, "app/src"),
path.resolve(__dirname, "app/test")
],
// "exclude" should be used to exclude exceptions
// try to prefer "include" when possible
// the "loader"
loader: "babel-loader" // or "babel" because webpack adds the '-loader' automatically
}
]
}
1) Correct.
2) Correct.
3) Correct.
4) I am unsure. My webpack.config.js file includes an output key, and does bundle it all into one file:
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js'
}
5) Correct.
6) This tells babel-loader what sort of transpile you want it to perform, as well as other compile options. So, for example, if you want it to transpile jsx as well + cache results for improve performance, you would change it to:
query: {
presets: ['react', 'es2015'],
cacheDirectory: true
}

Categories

Resources