I have decided to give it a try to Webpack 2. I'm trying to bundle js and css.
The problem is that CSS in not being applied the elements on the page (it is present in the built file).
This is the app structure:
app
|-styles.css
|-app.js
build
|-bundle.js
index.html
webpack config file:
var path = require('path');
module.exports = {
entry: './app/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
module: {
rules: [
{
test: /\.css$/,
use: 'css-loader'
}
]
}
}
index.html:
<html>
<head>
<script src="./build/bundle.js"></script>
</head>
<body>
<div class="abc"> hello </div>
</body>
app.js:
require('./styles.css');
console.log('js loaded!');
When I run build command getting this output:
[0] ./app/styles.css 240 bytes {0} [built] [1] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built] [2] ./app/app.js 148 bytes {0} [built]
Also I can see the css is included in the bundle.js file
exports.push([module.i, ".abc {\r\n width: 300px;\r\n height: 100px;\r\n background-color: red;\r\n}", ""]);
If I include css file in html it works fine so I guess there is no spelling mistake in CSS itself. I spent quite a lot of time trying to figure it out. Is there anything I'm missing?
To be able to use CSS in your webpack app, you need to set up a new loader. Out-of-the-box, webpack only understands Javascript and JSON. With a loader, you can translate another type of file to a format that webpack understands and can work with. There are many webpack loaders and each loader has a specific purpose.
By default, Webpack will inline your CSS as Javascript tags that injects the CSS into the page. This sounds strange but it lets you do hot reloading in development. In production you extract them to a file using the ExtractTextPlugin, and require it with a normal link tag.
You're loading the CSS as a string with just css-loader
. You'll need style-loader
as well in order to have the CSS load into the DOM when you import it.
use: [ 'style-loader', 'css-loader' ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With