Npm package include images in CSS - javascript

I have an npm package with this structure:
--src
--styles
-image.png
-style.scss
The style.scss file is referencing the image like this:
.test {
background-image: url(./image.png);
}
The problem is when I consume the package, CSS is looking the image from the root and not relative to my package, how we can solve this issue?
This is how I'm importing the package:
#import "mypackage/src/styles/style";

I have this issue too and I do not find a elegant way to this issue. Finally I copied the referenced files to the build directory to solve this issue. The "copy-webpack-plugn" plugin was used(https://github.com/kevlened/copy-webpack-plugin)
You may refer to the following issue too(
Include assets from webpack bundled npm package)

All you need just install file loader like this.
npm install file-loader --save-dev
and then add this line to module part in your config :
module: {
rules: [{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
}]
}

I have had this issue recently and the information on StackOverflow was outdated (as expected, this is a question that relates to NPM & Web Development and everything moves fast in this space).
Fundamentally, this problem is solved entirely by Webpack 5 as it comes out of the box. Only the webpack.config.js file needs to be updated.
The part of webpack's documentation that relates to this is here: https://webpack.js.org/guides/asset-modules/
What you want to do is Base64 encode your static assets and inline them to your CSS/JavaScript.
Essentially, when you are packing up your source code to distribute it on NPM, and you have some CSS file which refers to static images as such: background-image: url(./image.png) what you need to do is inline your assets to your style file, and then process your style file with the style-loader and css-loader packages.
In short, making my webpack.config.js contain the lines below solved my issue and allowed me to export one single index.js file with my package, which I imported into my other projects.
What really matters here is the type: asset/inline line, when we are testing for images.
webpack.config.js
...
...
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.(png|jpg|gif)$/i,
type: "asset/inline",
},
],
},
...
...

Related

what's the workflow of style-loader and css-loader

I'm new to webpack, still a little bit confused that how webpack cooperate with loaders. Let's we have below typescript file index.ts:
//index.ts
import "bootstrap/dist/css/bootstrap.css";
...
// typescript code
and below is the webpack config file:
module.exports = {
mode: "development",
entry: "./src/index.ts",
output: { filename: "bundle.js" },
resolve: { extensions: [".ts", ".js", ".css"] },
module: {
rules: [
{ test: /\.ts/, use: "ts-loader", exclude: /node_modules/ },
{ test: /\.css$/, use: ["style-loader", "css-loader"] }
]
}
};
Below is my personal thought on how webpack works with loaders, please correct me if I'm wrong:
Step 1-Webpack encounter index.ts, so it passes this file to ts-loader, and ts-loader read the file and pass it to ts compiler, ts compiler generates js code file index.js and pass back to ts-loader, then ts-loader passes index.js back to webpack.
Step 2- Webpack reads index.js and needs to resolve the css file, so Webpack passes the task to css-loader, so css-loader reads the css file as a long long string, then passes the task to style-loader, which creates js code that can be embedded in tags in the index.html file.
Step 3- bundle.js is ready, and client sends a http request to get index.html, and the bundle.js is fetched and create a <style> tags to include all css styles.
Is my above understanding correct? If yes, below is my questions:
Q1-after style-loader generates js code, does it pass those js code back to css-loader, then css-loader passes received js code to webpack? or style-loader pass generated js code to webpack directly?
Q2- in the webpack config file:
...
{ test: /\.css$/, use: ["style-loader", "css-loader"] }
...
it seems that the style-loader is used first, then css-loader steps in( I have tried this approach, it worked, not sure why it worked)
isn't that the css-loader should start to work first then style-loader as:
...
{ test: /\.css$/, use: ["css-loader", "style-loader"] }
...
Is my above understanding correct?
Yes
Q1-after style-loader generates js code, does it pass those js code back to css-loader, then css-loader passes received js code to webpack? or style-loader pass generated js code to webpack directly?
Answer: style-loader pass generated js code to webpack directly
Q2 it seems that the style-loader is used first, then css-loader steps in,
It can seem wrong. But its one of those things you need to read the docs for. The last thing to process it is mentioned at the top of the array. Personally I don't think the other way around would be any more intuitive.

why we need to exclude node_modules in webpack?

below is a webpack config file:
module.exports = {
mode: "development",
entry: "./src/index.ts",
output: { filename: "bundle.js" },
resolve: { extensions: [".ts"] },
module: {
rules: [
{ test: /\.ts/, use: "ts-loader", exclude: /node_modules/ }
}
]
}
};
I don't understand why we need to exclude node_modules when dealing with typescript files? Below is my points:
1-Firstly, nearly all packages are written in js not in ts, it is not going to harm if we include node_modules.
2-If we are referencing a package that is written in ts, we definitely want ts code to be compiled to js code, then we have to include node_modules to make sure everything works, don't we?
1-Firstly, nearly all packages are written in js not in ts, it is not going to harm if we include node_modules.
Excluding node_modules at the transpiling stage increases performance which could otherwise get a hit.
If we are referencing a package that is written in ts, we definitely want ts code to be compiled to js code, then we have to include node_modules to make sure everything works, don't we?
Yes, and then is the key here. Excluding node_modules at the transpiling stage doesn't prevent webpack from using its content at the bundling stage.

Webpack - Bundle multiple/different versions of .css files

I would like to make my bundled .css file being generated by Webpack more configurable, so I can output different 'versions' - based on the same .css file - to make the life of developers working on my project in the future easier.
I would like to have the following steps:
Concat of all SCSS into CSS (bundle.css)
Minimize output of step 1 (bundle.min.css)
Embed all images from step 2 (bundle.b64.min.css)
Embed all fonts from step 3 (bundle.bs64.fonts.min.css)
In the end - after my build process -, I would have 4 distinct files in my dist folder. Would that me possible?
The way I'm currently doing it, I run a different script for each step - deletes dist folder, goes through project, produces the output. I would like to have a single script that does all of it at once without having to go through my project 4 times.
I kind of found a solution for it here:
Webpack Extract-Text-Plugin Output Multiple CSS Files (Both Minified and Not Minified)
But, for my specific case, I would have to return 4 different configurations in a array instead of a single object.
Ok so based on our comment conversation i'm gonna give you a workflow of steps 1-4, but with regular assets handling, not a bundling of assets (which i haven't heard of but maybe someone else can elaborate there).
So the steps:
bundle all scss files into 1 bundle.css
make sure this bundle is minified
add assets management to build for images
add assets management to build for fonts
The important things:
This workflow is basically a built by configuration. configuring the npm scripts with the package.json file, and configuring webpack with config.webpack.js. This will allow you to simply run 1 command to build your project: npm run build. note: For simplicity's sake i am going to ignore production/development/etc environments and focus on a single environment.
package.json:
This is used to set up the command that will actually run when you input npm run build in the terminal (from the project dir of course).
since we are avoiding different environments for now and as you are not using Typescript this is a very simple configuraton:
"scripts": {
"build": "webpack",
},
that's all you have to add. It sound's stupid now but when the project will get more complex you are going to like those scripts so better start off making them already.
webpack.config.js:
The major lifting will be made in this configuration file. This basically tells webpack what to do when you run it (which is what npm run build is doing).
first off let's install some plugins:
npm install --save-dev file-loader
npm install --save-dev html-webpack-plugin
npm install --save-dev mini-css-extract-plugin
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'production',
devtool: 'source-map'
entry: './client/src/app.jsx',
output: {
path: path.join(__dirname, 'client/dist/public'),
filename: 'bundle.[hash].js'
},
module: {
rules: [
{
test: /\.s?css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: false
}
},
'css-loader',
'sass-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
]
},
resolve: {
extensions: ['.js', '.json', '.jsx']
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './client/src/index_template.html'
}),
new MiniCssExtractPlugin({
filename: 'style.[hash].css',
chunkFilename: '[id].[hash].css'
}),
]
};
Notice i've added the htmlWebpackPlugin because it makes it easier to reference the correct hashed bundles automatically. Also I've assumed the app is a react app but you can just change the entry point to where your app loads from.
This is quite hard to do of the fly without testing things out, but i hope this gives you enough reference as to what you should change and do to get going with it.
Again i strognly recommend the webpack.js guides and documentation, they are very thorough and once you start getting the hang of it things start working smoothly.

What webpack4 loader is used to load *.svg files, *.gif, *.eot?

I'm developing a react UI component and it depends on another UI component (react-widgets/lib/DropDownlist). This javascript module has resources that end with these file extensions: *.gif, *.eot, *.svg, *.woff, *.ttf.
Webpack4 is complaining that it doesn't know how to process these file types and that I might need a loader to handle these file type. One error is:
Error in .../react-widgets/dist/fonts/rw-widgets.svg?v=4.1.0
Module parse failed: ...
**You may need an appropriate loader to handle this file type.**
So I need to update my webpack.config.js file with the appropriate loaders for those file types. My config is based off of this. Side Note: A
shout out goes to Mark England who wrote this article which does a fantastic job for how to create a reusable component.
The relevant snippet is:
// Snippet from Mark's code webpack.config.js
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: "babel-loader",
exclude: /node_modules/
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
I know what the syntax for webpack is to define the loaders but I don't know what loaders to use. But this sample webpack config file didn't include support for these other file types.
What have I done to try and solve the problem
I generally use create-react-app so I avoid this problem altogether. :-) It, however, doesn't allow me to create react libraries for distribution (AFAIK).
First I searched on the net webpack *.gif loader. Nothing useful.
Next I searched for webpack loaders based on file type. This gave some good results that describe the loader syntax, pointed me to some loaders file-loader and how to use them, and this question on SO that helps me realize the *.svg loader might be what I need to load svg files.
{test: /\.svg$/, use: "svg-inline-loader"},
So I might be able to use svg-inline-loader for the *.svg files.
I can repeat this approach for all of the file types.
The next approach is to examine Create React App (CRA)
I primarily develop in react, and look at the CRA webpack config files (because the create-react-app appears to stay leading edge on these topic). So I can see the url-loader is used for images (based on what the node_modules/react-scripts/config/webpack.config.dev.js file is using).
Another one down...
My question
Does webpack (or another website) have a table that lists the loaders available for given file types?
For example,
know good image loaders for the following file types are:
Webpack 4
*.gif, *.jpg => url-loader
*.svg => svg-inline-loader
*.eot => ???
I realize that because webpack is more of a plugin/loader architecture that it might not be webpacks place to have this list so another website might need to have it.
When you need a loader what do you do?
If there is no central place to look for this answer, then please share how you find loaders that are needed to solve your webpack file loading problem.
It all depends on your workflow, how u want to load assets at run-time.
For eg, if u have lot of images, it might be a good idea to use a file-loader and place them directly inside the build directory.
The above approach will increase the GET calls and the bundled js file size will not be affeted
If u have less images/small size images then you can use url-loader which converts them into data-URL and put them inside your bundled js files.
The above approach will reduce the GET calls and will slightly increase the bundled js size.
If u want combination of both, then u can set a size limit and fallback loader(file-loader) on url-loader. What this will do is, the size of the dataURL will be calculated.If the size is grater than the limit, the file-loader will be used, which will place it in the build directory.
How I use them
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'images/',
name: '[name][hash].[ext]',
},
},
],
},
{
test: /\.(svg)$/,
exclude: /fonts/, /* dont want svg fonts from fonts folder to be included */
use: [
{
loader: 'svg-url-loader',
options: {
noquotes: true,
},
},
],
},
{
test: /.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
exclude: /images/, /* dont want svg images from image folder to be included */
use: [
{
loader: 'file-loader',
options: {
outputPath: 'fonts/',
name: '[name][hash].[ext]',
},
},
],
}

Why is Webpack looking for a preset in my home directory?

In the Webpack for a project I'm working on, I have Webpack set to do Babel transpiling so I can use Flow-typed JavaScript. However, when I run Webpack, which has this rule,
{
test: /\.js/,
exclude: ['/node_modules/'],
use: [{
loader: 'babel-loader',
options: {
presets: ['env'],
plugins: ['transform-flow-strip-types']
}
}]
}
I'm getting:
Module build failed: Error: Couldn't find preset "transform-flow-strip-types"
relative to directory "/home/andy"
Last time I was working on this, Webpack worked correctly and was searching for transform-flow-strip-types in my node_modules folder, but now it's looking in my home directory. Why would Webpack all of a sudden by looking in my home directory, or how would I be able to diagnose why that is?
This is an unfortunate footgun in Babel's config file parsing. It has traversed all the way out of your project and found an unrelated .babelrc file that is in your home directory.
There's pretty much never a reason to have a .babelrc there, so your best bet would be to delete /home/andy/.babelrc. Alternatively if that's actually something your wanted (if so, please reconsider :P), you could create a no-op .babelrc in your project with just an empty object in it, which would also fix the issue.
I'm currently working to make Babel stop searching for .babelrc files as soon as it finds any package.json but that has yet to land and would only apply to Babel 7.x, not the current 6.x release. https://github.com/babel/babel/pull/7358

Categories