webpack not getting seperate css file for extract text plugin - css

Hi everyone I am using web-pack to try to replace a gulp build that was overly complicated. but was running into some issues when it came to the Css. We are using sass. We also have a project structure that has the sass files right by each of the the angular component so that means for every class there is a separate folder. Currently our gulp magically goes into the folders and downloads the sass.
But I can't get the extract-text-webpack-plugin to output me a separate Css file the source I am using for trying to do this is.
https://itnext.io/sharing-sass-resources-with-sass-resources-loader-and-webpack-ca470cd11746
here is my code
const config = {
entry: {
'app': './app/app.js',
// 'vendor': './src/vendor.module.js'
},
devtool: 'source-map',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist/dev')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: [ 'ng-annotate-loader', 'babel-loader' ]
},
// for fixing of loading bootstrap icon files
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=10000',
options: {
name: './fonts/[name].[ext]'
}
},
{
test: /\.(eot|ttf)$/,
loader: 'file-loader',
options: {
name: './fonts/[name].[ext]'
}
},
{
test: /\.html$/,
loader: 'html-loader',
options: {
attrs: [ 'attrs=false' ]
}
},
{
test: /\.scss$/,
use: ExtractTextWebpackPlugin.extract({
fallback: 'style-loader',
filename: path.resolve(__dirname, 'dist/dev') + 'app.css',
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'sass-loader'
},
{
loader: 'sass-resources-loader',
options: {
resources: require(path.join(process.cwd(), './app/appscss.js'))
}
}
]
}),
},
/* ,
{
test: /\.(scss)$/,
use: ExtractTextWebpackPlugin.extract({
use: [
{
loader: "css-loader",
options: {
minimize: true
}
},
{
loader: "sass-loader"
}
]
})
} */
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
comments: false,
sourceMap: true,
}),
new ExtractTextWebpackPlugin('app.css', {
allChunks: true
}),
new webpack.DefinePlugin({
GULP_REPLACE_ENV_URL: JSON.stringify(environementUrl())
})
],
devServer: {
port: 5000,
contentBase: path.resolve(__dirname, 'dist/dev'),
historyApiFallback: true,
// needed since we set api to something other than host
// http://flummox-engineering.blogspot.com/2017/10/webpack-dev-server-invalid-host-header-host-0.0.0.0-not-working-npm-dev-server.html
disableHostCheck: true
}
};
module.exports = config;
Any help would be much appreciated.

Related

How can I load CSS styles using Webpack in React app?

I am having an issue with my React app. I have added Webpack and it is compiling successfully but, at the moment of serving the content, the app shows no styles at all.
This is what I have so far in my webpack.config.js file:
const path = require('path');
const BUILD_DIR = path.resolve(__dirname + '/public/build');
const APP_DIR = path.resolve(__dirname + '/src');
// This is the main configuration object.
// Here, you write different options and tell Webpack what to do
module.exports = {
experiments: {
asyncWebAssembly: true,
topLevelAwait: true,
layers: true // optional, with some bundlers/frameworks it doesn't work without
},
resolve: {
extensions: ['', '.js', '.jsx', '.css']
},
// Path to your entry point. From this file Webpack will begin its work
entry: [APP_DIR + '/index.js', APP_DIR + '/index.css', APP_DIR + '/App.css'],
// Path and filename of your result bundle.
// Webpack will bundle all JavaScript into this file
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
// Default mode for Webpack is production.
// Depending on mode Webpack will apply different things
// on the final bundle. For now, we don't need production's JavaScript
// minifying and other things, so let's set mode to development
mode: 'development',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true,
},
},
{ loader: 'sass-loader' },
{ loader: 'postcss-loader' }
],
},
]
}
};
Is there anything I am missing to get my css to work? I only have two files, located at /src: App.css and index.css. None of them seem to be loaded and I have no errors in the console.
rules: [
{
test: /\.js|jsx$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.(sass|scss|less|css)$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.(png|jpe?g|svg|gif)$/,
loader: 'file-loader'
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader',
]
},
{
test: /\.css$/,
use: [
{
loader: 'url-loader',
options: {
limit: false
}
}
]
}
]

Webpack Image Path

I coded my site using Webpack. Everything works except the image's path. I'm used to write ../img/test.png for it work. I've researched other questions but none work.
My files are organized inside the dist folder of the wordpress theme.
Here's my webpack.config.js :
module.exports = {
mode: 'development',
entry: [
'./src/index.js'
],
devtool: "source-map", // any "source-map"-like devtool is possible
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
},
module:{
rules:[
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test:/\.(s*)css$/,
use: [{
loader: "style-loader", options: {
sourceMap: true
}
}, {
loader: "css-loader", options: {
sourceMap: true
}
}, {
loader: "resolve-url-loader", //resolve-url-loader needs to come *BEFORE* sass-loader
options: {
sourceMap: true
}
},{
loader: "sass-loader", options: {
sourceMap: true
}
}]
}
]
},
plugins: [
new CopyWebpackPlugin([
{from:'assets/images',to:'images'}
])
],
watch: true,
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
I've tried other url-loaders but nothing seems to work. Thanks in advance.
I figured it out. The public and output path were the most important things I had to learn. Since this was with Wordpress, the other answers weren't sufficient. The new config looks like:
const webpack = require('webpack');
const path = require('path');
module.exports = {
mode: 'development',
entry: [
'./src/index.js'
],
devtool: "source-map", // any "source-map"-like devtool is possible
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
},
module:{
rules:[
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.(png|jpe?g|gif)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'images',
publicPath: 'wp-content/themes/{{ THEME NAME }}/dist/images',
},
},
],
},
{
test:/\.(s*)css$/,
use: [{
loader: "style-loader", options: {
sourceMap: true
}
}, {
loader: "css-loader", options: {
sourceMap: true
}
}, {
loader: "sass-loader", options: {
sourceMap: true
}
}]
}
]
},
watch: true,
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
Hope this helps for anyone who is working through this.

MiniCssExtractPlugin + SplitChunksPlugin doesn't put scoped css into bundle

I'm using a Webpack 4 setup, where I'm trying to get all my css into a single bundle, including my scoped css from .vue files. I'm using MiniCssExtractPlugin to extract the css from the files and SplitChunksPlugin to bundle all the css into a single file. The problem is that my scoped css from .vue files is being put into separate css files.
My webpack config:
optimization: {
splitChunks: {
cacheGroups: {
common: {
test: /[\\/]node_modules[\\/].*\.js$/,
name: 'common',
chunks: 'all'
},
styles: {
test: /\.css$/,
filename: '[name]-[contenthash].css',
chunks: 'all',
enforce: true
}
}
}
},
module: {
rules: [
{
enforce: 'pre',
test: /\.(js|vue)$/,
exclude: /node_modules/,
use: 'eslint-loader'
},
{
test: /\.vue$/,
use: 'vue-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.(sa|sc|c)ss$/,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
importLoaders: 3,
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
indentedSyntax: true
}
}
]
}
]
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css'
}),
new PurifyCSSPlugin({
paths: glob.sync([
path.join(__dirname, 'templates/**/*.html'),
path.join(__dirname, 'assets/js/**/*.js'),
path.join(__dirname, 'assets/js/**/*.vue')
]),
purifyOptions: {
info: true,
minify: true,
rejected: true
}
})
],
resolve: {
alias: {
jquery: 'jquery/src/jquery',
'vue': 'vue/dist/vue.js'
},
extensions: ['.js', '.vue', '.json', '.sass']
}
Output:
scoped-css-from-a-vue-file.03371a6565c9f56951dd.css // (172 bytes)
main-css-bundle-from-sass-files.af5152091d41a56d9bdd.css // (303 KiB)

Getting webpack style loader to let me import css within my components

I'm currently messing around with https://github.com/sahat/megaboilerplate and trying to get it such that I can import css from within my components.
Here's my config:
const path = require('path');
const webpack = require('webpack');
var config = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./app/main'
],
output: {
path: path.join(__dirname, 'public', 'js'),
filename: 'bundle.js',
publicPath: '/js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
],
module: {
loaders: [
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
],
}, {
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
plugins: [
['react-transform', {
transforms: [
{
transform: 'react-transform-hmr',
imports: ['react'],
locals: ['module']
}, {
transform: 'react-transform-catch-errors',
imports: ['react', 'redbox-react']
}
]
}]
]
}
}
]
}
};
if (process.env.NODE_ENV === 'production') {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
screw_ie8: true,
warnings: false
}
})
);
}
module.exports = config;
As you can see from the original config:
https://github.com/sahat/megaboilerplate/blob/master/webpack.config.js
I've added:
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
],
But when I run the server, I get:
/megaboiler/node_modules/spectre.css/dist/spectre.min.css:1
(function (exports, require, module, __filename, __dirname) { /*! Spectre.css | MIT License | github.com/picturepan2/spectre */html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,footer,header,nav,section{display:block}h1{font-size:2em;margin:.67em 0}figcaption,figure,main{display:block}hr{box-sizing:content-box;height:0;overflow:visible}a{background-color:transparent;-webkit-text-decoration-skip:objects}a:active,a:hover{outline-width:0}b,strong{font-weight:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}dfn{font-style:italic}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}audio,video{display:inline-block}audio:not([controls]){display:none;height:0}img{border-style:none}svg:not(:root){overflow:hidden}button,input
SyntaxError: Unexpected token {
What am I missing?
Your test: /\.css$/ is now.
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
],
Seems that you may miss some loaders which can handle your files correctly, remember each loader has it's limits what it can process.
use: [
'raw-loader',
'style-loader',
'css-loader',
'postcss-loader',
'resolve-url-loader',
]

PostCSS & Webpack configuration

I'm really disheartened, because I can't find any useful resource on the subject.
I merely want to watch my .css files, use post css' plugins to transform them and finally export them to my /public folder as I already do with my .jsx files
Here's my web pack configuration
const path = require('path');
const webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: path.resolve('src/index.jsx'),
output: {
path: path.resolve('public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
devServer: {
publicPath: "/",
contentBase: "./public"
},
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}, {
loader: 'postcss-loader',
options: {
plugins: function() {
return [require('lost'), require('postcss-cssnext'), require('postcss-import')]
}
}
}
]
})
}, {
test: /\.jsx?$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015', 'react']
}
}
],
exclude: /(node_modules|bower_components)/
}
]
},
plugins: [new ExtractTextPlugin("main.css")]
}
I assume you are using webpack2
If you want your css file dumped out separately, you would need ExtractTextPlugin. Here is my css loader which works
I define the post css plugins right within the webpack config, because then it stays in one place. Hope this helps:
var ExtractTextPlugin = require('extract-text-webpack-plugin');
...
...
module.exports = {
...
...
module: {
rules: [
...
...
{
test: /\.css$/,
exclude: /node_modules/,
loader: ExtractTextPlugin.extract(
{ fallback: 'style-loader',
use: [{
loader: 'css-loader',
options: {
modules: true,
localIdentName:'[name]__[local]___[hash:base64:5]'
}
},
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [
require('autoprefixer')
]
}
}
},
]
})
},
}
Maybe your plugins are incorrectly created.
Try
return [require('lost')(), require('postcss-cssnext')(), require('postcss-import')()]
(Note the () to invoke the plugin creation).
Also are you actually using import/require() to include your css? If not you should, no magic stuff will glob your css :)

Resources