Using CSS in Webpack - javascript

I've inherited a web app that uses webpack. In my app, I have a directory called "pub", which looks like this:
./pub
/styles
app.css
/images
brand.png
I have been trying unsuccessfully all morning to use these via webpack. In my webpack.config.js file, I have the following:
const path = require('path');
const projectRoot = path.resolve(__dirname, '../');
module.exports = {
entry: {
app: './src/index.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192
}
}
]
}
]
}
};
Then, in my index.js file, I have the following:
import logoImage from './public/images/brand.png';
require("css!./public/css/app.css");
When I run webpack, I receive an error that says:
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.
You need to specify 'css-loader' instead of 'css',
see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
I don't really understand this error. When I look at it, and then I look at my webpack.config.js file, it looks to me like I'm using css-loader. Beyond that though, how do I use a style in my webpage once the require statement is working. I'm just trying to use webpack with a web app and want to import my brand and CSS and I can't figure it out.

You don't need the css! in your require statement
require("css!./public/css/app.css");
You can just use
require("./public/css/app.css");
Because you are testing files with:
{
test: /\.css$/, // <-- here
loader: "style-loader!css-loader"
},
Or without the rule in your webpack config
// No test in rules matched but you tell webpack
// explicitly to use the css loader
require("style-loader!css-loader!./public/css/app.css");

Your hierarchy is pub/styles/app.css but the location you use in your require is public/css/app.css. It looks like you're trying to call your css from the wrong location.
If this doesn't solve your issue, check out this link https://webpack.github.io/docs/stylesheets.html
The first step on that page is to install css-loader and configure it, this might be a good place to start.

Related

Styles not inserted into HEAD using Webpack MiniCssExtractPlugin with Create React App

I'm using create-react-app to create a component library using Storybook JS. The aim is to publish a NPM package where these components can be used in other projects. SASS is being used for this library, with global variables defined and imported into the src/index.js file.
I'm at the point of testing my NPM package, and trying to bundle it with Webpack V4. This has been semi-successful using npm link on another local project. However, I'm facing an issue with MiniCssExtractPlugin where the styles are not being inserted at all into the HEAD of this project.
The SASS stylesheets are converted into CSS and added to the dist/ folder of my component library project with no issues. But these don't get applied anywhere when importing components via the NPM package to my other project, e.g. import { Button } from '#my-account/components';
There are no issues on my dev environment when using style-loader, and the styles are inserted straight into the DOM with a <style> tag. I'm sure I must be missing something, but I feel like I've exhausted everything to try diagnose this. Is create-react-app not compatible with this plugin? Or are styles not automatically injected to the HEAD of projects via NPM packages with this plugin?
The styling does work if I import the file from the NPM package into my local project, e.g. import '#my-account/components/dist/main.cd2be00655e79c5077cb.css'; - but this doesn't seem maintainable if styles are regularly updated and the file uses a hash in its name?
I attempted to add HtmlWebpackPlugin to create an index.html file, but this didn't resolve the issue.
Any help would be greatly appreciated!
webpack.config.prod.js
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'production',
devtool: 'source-map',
entry: './src/index.js',
output: {
path: path.resolve('dist'),
filename: 'index.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules)/,
use: 'babel-loader',
}
],
rules: [
{
test: /\.scss$/,
sideEffects: true,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-resources-loader',
options: {
resources: require(path.join(process.cwd(), 'src/assets/sass/WebpackStyles.js')),
hoistUseStatements: true
}
}
],
},
]
},
resolve: {
extensions: ['.js'],
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: '[name].[hash].css'
})
]
};
Component libraries regularly require css to be imported alongside the js in order to work properly. If you update your plugins as:
new MiniCssExtractPlugin({
filename: '[name].css'
})
Then you can instruct consumers of your library to add import '#my-account/components/dist/main.css' which is a little easier to swallow. I'm not sure there's a magical way to have the styles just show up without extensive custom webpack loaders in your consumers.

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/"
},

Concat and minify all less files with Webpack without importing them

I have a folder of around 20 separate less files that I need to concatenate into a single file via Webpack and store this in my /dist folder. My current Webpack config file is as follows:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const bundleOutputDir = './wwwroot/dist';
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
return [{
stats: { modules: false },
entry: { 'main': './ClientApp/boot.ts' },
resolve: { extensions: ['.js', '.ts'] },
output: {
path: path.join(__dirname, bundleOutputDir),
filename: '[name].js',
publicPath: '/dist/'
},
module: {
rules: [
{ test: /\.ts$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.html$/, use: 'raw-loader' },
{ test: /\.css$/, use: isDevBuild ? ['style-loader', 'css-loader'] : ExtractTextPlugin.extract({ use: 'css-loader' }) },
{ test: /\.less/, use: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader') },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [
new CheckerPlugin(),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('site.less'),
new ExtractTextPlugin('site.css')
])
}];
};
If I try and import each single .less file into the boot.ts entry file, I get a less error stating that the less variables that I've declared are not being recognised, which is how I came to the conclusion that I need to concat these files beforehand. I come from a gulp background, so any help to get me up and running with this would be greatly appreciated.
If there is an alternative way to get all less compiled to css and working correctly, without the need for concat, then I'm open to suggestions.
Webpack is a module bundler and uses the module syntax for JavaScript (ES6, CommonJS, AMD..), CSS (#import, url) and even HTML (through src attribute) to build the app's dependency graph and then serialize it in several bundles.
In your case, when you import the *.less files the errors are because you miss CSS modules. In other words, on the places where you have used variables defined in other file, that file was not #import-ed.
With Webpack it's recommended to modularize everything, therefore I would recommend to add the missing CSS modules. I had the same issue when I was migrating a project from Grunt to Webpack. Other temporary solution is to create an index.less file where you will #import all the less files (note: the order is important) and then import that file in app's entry file (ex. boot.ts).

Using Webpack custom loader in loaders array

I am trying to build a Webpack custom loader:
module.exports = function(source) {
// Transform the source and return it
console.log('$$$$$$$$$$$$$$$$$$$$$');
return source;
};
Now, I want to use it in my loaders array, something like:
loaders: [
{test: /\.vm$/, loader: 'vm-loader', exclude: [/node_modules/, /dist/]}
]
I tried to use resolveLoader's alias, but it did not work:
resolveLoader: {
alias: {
"vm-loader": path.join(__dirname, "./lib/velocity-plugin")
},
root: [
path.join(__dirname, 'node_modules'),
path.resolve('./node_modules')
]
}
What Am I missing?
Answering my own question:
As it turned out, my custom loader doesn't work because webpack does not work on files which where not required. In my case those html/vm files are not required and not part of the bundle (they are rendered by the server).
My solution was adding gulp in order to have this working. Another (hacky) solution will be using this method

Include assets from webpack bundled npm package

I've been banging my head over this for a while, and am wondering if it's even possible to begin with. Thanks for any help with this!
The npm package
I've got an npm package which is basically a library of React components. This library has embedded stylesheets, which references assets like fonts and images from the CSS. These are then all bundled using webpack into my-package.js.
The config for this looks like:
var path = require('path');
module.exports = {
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel-loader'],
exclude: /node_modules/
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
loader: 'file-loader'
},
{
test: /\.styl$/,
loader: 'style-loader!css-loader!stylus-loader'
}
]
},
entry: [
'./lib/components/index.js',
'./lib/index.styl'
],
output: {
path: path.join(__dirname, 'build/'),
filename: 'my-package.js'
}
}
With ./lib/components/index.js looking like:
import '../index.styl';
import MyComponent from './my-component.js';
export {
MyComponent
}
So far, so good.
The application
Now in another code base I've got the main application, which install this npm package.
My application root requires this package...
import MyPackage from 'my-package';
And is then itself webpack bundled and loaded onto the browser. All the scripts and style blocks are bundled correctly, however the styles which reference the assets are using the relative url from the npm package itself, therefore giving me 404s from the application.
console errs
Is there any way to tell webpack to resolve these images from node_modules/my-package/build/[webpack-generated-name].jpg ?
My application's webpack config looks like this:
var path = require('path'),
webpack = require('webpack');
module.exports = {
devtool: '#eval-source-map',
entry: [
'my-package',
'webpack/hot/only-dev-server',
'./app/index.js',
],
output: {
path: path.join(__dirname, 'build/static'),
filename: 'bundled.js',
publicPath: '/',
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
resolve: {
extensions: ['', '.js']
},
resolveLoader: {
'fallback': path.join(__dirname, 'node_modules')
},
module: {
loaders: [
{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/,
include: __dirname
},
{
test: /\.css?$/,
loader: "style-loader!css-loader",
include: __dirname
},
{
test: /\.(jpg|jpeg|ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader'
},
{
test: /\.styl$/,
loader: 'style-loader!css-loader!stylus-loader'
}
]
}
};
Figured out a way around this.
In my application's webpack config I added a plugin (recommended by #Interrobang) which copies the static assets from the node_module/my-package into the app server's public path:
var TransferWebpackPlugin = require('transfer-webpack-plugin');
...
plugins: [
new TransferWebpackPlugin([
{ from: 'node_modules/my-package/assets', to: path.join(__dirname, 'my/public') }
])
]
...
These will then be made accessible by calling the asset name: localhost:XXXX/my-image.jpg. The server here is basically looking at /my/public/my-image.jpg if you've set it up correctly.
I'm using Express, so I just had to define app.use(express.static('my/public')) in my app server.
When bundling your NPM package, you could inline all the static assets into your final bundle. That way, your index.js that Webpack bundles for you would have all the static assets it needs, and simply importing that wherever you need your React components would do the trick.
The best way to inline static assets as of Webpack 5 is by using the "asset/inline" module from Asset Modules, which you can read about here: https://webpack.js.org/guides/asset-modules/
Simply put, your webpack.config.js should have a section as such:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
type: 'asset/inline'
}
]
},
};
What really relates to your question here is the test for png, jpg, and gif files which uses the asset/inline module.
The post here https://stackoverflow.com/a/73417058/14358290 explains it with slightly more detail.
Other plugins that copy such files from your /node_modules to /build directory are hacky and create packages that are not really distributable - everyone else that uses the said package would have to set up their Webpack to do the same copying operation. That approach can be avoided now that Webpack 5 solves this problem for us.

Categories

Resources