webpack: Inline css for a splash screen (above the fold css) - webpack-2

Im trying to figure out why a css segment will not run through 'style-ext-html-webpack-plugin'.
Currently I have a .CSS file with rules for the splash screen.
It's being extracted using 'extract-text-webpack-plugin' and injected to the template's <head> with 'extract-text-webpack-plugin'.
problem is, the file never gets run through 'style-ext-html-webpack-plugin' and I can't wrap my head around how to debug it.
(Ideally, I'd like to have a .SCSS file so it can be themeable through a .env file. i.e: have splash.scss exclusively extracted and inlined in the <head> after being injected with some theme colors)
webpack.config.js:
....
const ExtractTextPlugin = require('extract-text-webpack-plugin'); //used for above-the-fold css (such as splash-screen)
const StyleExtHtmlPlugin = require('style-ext-html-webpack-plugin');
const extractSplashCSS = new ExtractTextPlugin('splash.css');
module.exports = {
entry: {...},
output: {...},
resolve: {...},
plugins: [
...,
new HtmlWebpackPlugin({
title: enviroments.TITLE,
splashScreenTitle: enviroments.SPLASH_SCREEN_TITLE,
template: 'src/index.html',
cache: true,
favicon: enviroments.FAVICON || './src/assets/images/favicon.ico',
inject: 'body'
}),
extractSplashCSS,
new StyleExtHtmlPlugin('splash.css')
],
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{
test: /\.css$/,
loader: 'style-loader!css-loader!resolve-url-loader?import=false',
exclude: [path.join(path.resolve('./src'), 'common/app/splash.css')]
},
{
test: /\.css$/,
loader: extractSplashCSS.extract({
use: 'css-loader'
}),
include: [path.join(path.resolve('./src'), 'common/app/splash.css')]
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader?importLoaders=1',
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [require('autoprefixer')];
}
}
},
'resolve-url-loader?sourceMap',
{
loader: 'sass-loader?sourceMap',
options: {
includePaths: path.resolve('./src'),
data: `
$color-primary: ${theme.PRIMARY};
....
`
}
}
]
},
....
]
}
};
index.js:
...
// above the fold css
import 'common/app/splash.css';

Needed to update html-webpack-plugin to 2.29.0.
I've managed to solve this issue, using a sass file that can be themeable with variables from .env file:
I had to explicitly exclude the splash file from the normal sass flow and create another loader definition explicitly for it:
...
const ExtractTextPlugin = require('extract-text-webpack-plugin'); //used for above-the-fold css (such as splash-screen)
const StyleExtHtmlWebpackPlugin = require('style-ext-html-webpack-plugin');
module.exports = {
...
plugins: [
...
new HtmlWebpackPlugin({
...
}),
new ExtractTextPlugin('splash.css'),
new StyleExtHtmlWebpackPlugin('splash.css'),
],
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.css$/, loader: 'style-loader!css-loader!resolve-url-loader?import=false' },
{
test: /\.scss$/,
exclude: [path.join(path.resolve('./src'), 'common/app/splash.scss')],
use: [
.....
]
},
{
test: /\.scss$/,
include: [path.join(path.resolve('./src'), 'common/app/splash.scss')],
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: {minimize: true}
},
{
loader: 'postcss-loader',
options: {
plugins: function() {
return [require('autoprefixer')];
}
}
},
{
loader: 'sass-loader',
options: { data: `$color-primary: ${theme.PRIMARY};` }
}
]
})
},
]
}
};

Related

Adding autoprefixer to webpack 2.2.1

I'm trying to add autoprefixer to webpack 2.2.1 and having issues seeing the prefixes.
I installed postcss-loader https://github.com/postcss/postcss-loader as this seems to be the listed way to handle postcss in webpack.
I'm currently using scss files which I'm importing into my react files.
example: import styles from '../../styles/header.scss';
This is handled in webpack using sass-loader.
I'm not getting any error with my setup but I'm also not seeing any autopre-fixing going on to my files ? I presume this only needs to be added in development not production ?
Here is my dev setup webpack config.
const path = require('path')
const webpack = require('webpack')
const ROOT_DIR = path.resolve(__dirname, '../app')
module.exports = {
devtool: 'eval',
entry: [
`${ROOT_DIR}/js/index`,
'webpack-hot-middleware/client'
],
output: {
path: path.resolve(__dirname, '../public'),
filename: 'bundle.js',
publicPath: '/public/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.DefinePlugin({
"config.ASSET_URL": JSON.stringify(process.env.ASSETS_URL),
"config.GA_TRACKING_ID": JSON.stringify(process.env.GA_TRACKING_ID)
})
],
module: {
loaders: [
{ test: /\.js?$/,
loader: 'babel-loader',
include: path.join(__dirname, '../app'),
exclude: /node_modules/
},
{ test: /\.scss?$/,
include: path.join(__dirname, '../app', 'styles'),
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: { plugins: [
require('autoprefixer')
] }
},
{
loader: 'sass-loader',
options: {
data: "$assetPath: '" + process.env.ASSETS_URL + "';"
}
}
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
include : path.join(__dirname, '../app', 'images'),
loader : 'file-loader?limit=30000&name=[name].[ext]'
},
{
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
include : path.join(__dirname, '../app', 'fonts'),
loader: 'file-loader?name=fonts/[name].[ext]'
}
]
}
}
I had a to deal with sometime similar recently. Check if it works if you create a separate postcss.config.js file in the directory of your scss files with this in it
//postcss.config.js
module.exports = {
plugins: [
require('autoprefixer')
]
}
and in your webpack config
{ test: /\.scss?$/,
include: path.join(__dirname, '../app', 'styles'),
use: [
{loader: "style-loader"},
{loader: "css-loader"},
{loader: "postcss-loader"},
{loader: "sass-loader",
options: {
data: "$assetPath: '" + process.env.ASSETS_URL + "';"
}
}
]
},

Openlayers inherits method undefined in custom control loaded via shimming in webpack

I try to include the LayerSwitcher Custom Control with webpack in my project, but I always receive the error that ol.inhereitsis undefined in this line:
ol.inherits(ol.control.LayerSwitcher, ol.control.Control);
https://github.com/Viglino/ol3-ext/blob/ddc2f631348f8b1cfb5d24e8cf83ed13c262411d/dist/ol3-ext.js#L94
I already debugged this in firefox 57 (See screenshot) and I don't know why the method is not found, although the module is initialized/imported.
Is there missing something?
My webpack config is the following:
const path = require('path');
var webpack = require("webpack");
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'var',
library: 'IndexJS'
},
devtool: 'source-map',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ['env']
}
}
],
rules: [
{
test: require.resolve("./ol3-ext-1.0.1/dist/ol3-ext.js"),
loader: "imports-loader?$=jquery,ol=ol,ol.control=ol/control"
},
{
test: require.resolve("./ol3-ext-1.0.1/dist/ol3-ext.js"),
loader: "exports-loader?LayerSwitcher=LayerSwitcher,LayerPopup=LayerPopup"
}
]

Webpack error 'Error: Final loader didn't return a Buffer or String' when trying to compile React server side components using ReactJS.NET and MVC 5

I am getting the following error - 'Module build failed: Error: Final loader didn't return a Buffer or String' when trying to compile JSX components for server-side rendering using Webpack 2 and ReactJS.NET. I have followed the examples as described here as well as in this example.
My folder structure is similar to the Github example, I have one React component, an index.js file and a server.js file. Here are the contents:
/Content/components/TestComponent.jsx
var React = require('react');
class Test extends React.Component {
getInitialState() {
return { data: this.props.greeting };
}
render() {
return (
<div>
<h1>{this.props.greeting}</h1>
</div>);
}
}
module.exports = Test;
/Content/components/index.js
module.exports = {
Test: require('./TestComponent.jsx')
}
/Content/server.js
var Components = require('expose?Components!./components');
And here is my full webpack.config.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './Content/server',
output: {
path: __dirname + '/resources/dev/scripts/server',
filename: 'test.js'
},
module: {
rules: [
{
test: /\.js$|.jsx$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env', 'react'],
}
}
{
test: require.resolve('react'),
loader: 'expose?React'
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
externals: {
react: 'React'
}
}
I have created an example project here with the same problem.
The solution was to do away with the /Content/server.js file, and instead use the expose-loader in webpack. Here is the updated webpack.config.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './Content/components/index',
output: {
path: __dirname + '/resources/dev/scripts/server',
filename: 'test.js'
},
module: {
rules: [
{
test: /\.js$|.jsx$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env', 'react'],
}
},
{
test: require.resolve('./Content/components/index'),
use: [{
loader: 'expose-loader',
options: 'Components'
}]
},
{
test: require.resolve('react'),
use: [{
loader: 'expose-loader',
options: 'React'
}]
}
]
},
resolve: {
extensions: ['.js', '.jsx']
}
}

PostCSS CSSNext #media and color() not working with webpack 2

I'm upgrading a project from webpack 1 to 2, and am seeing some strange behavior with postcss-cssnext where some css next features, most notably color() functions and all my #media queries just aren't working anymore.
My webpack config with webpack 2 looks like this. What am I doing wrong here?
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
localIndentName: 'localIdentName=[name]__[local]___[hash:base64:5]',
sourceMap: true,
modules: true,
importLoaders: 1
}
},
{
loader: 'postcss-loader',
options: {
plugins: [
postcssImport({ path: './app/css/common' }),
postcssCssnext({ browsers: ['> 1%', 'last 2 versions'] }),
postcssReporter({ clearMessages: true })
]
}
}
]
}
postcss-loader is probably responsible for this change (1.3.x).
According to doc, you should use a function for "plugins" option.
Or use an array but in a postcss.config.js file.
module.exports = {
module: {
rules: [
{
test: /\.css/,
use: [
…
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [
postcssImport({ path: './app/css/common' }),
postcssCssnext({ browsers: ['> 1%', 'last 2 versions'] }),
postcssReporter({ clearMessages: true })
];
}
}
}
]
}
]
}
}
Or via postcss.config.js
module.exports = {
plugins: [
postcssImport({ path: './app/css/common' }),
postcssCssnext({ browsers: ['> 1%', 'last 2 versions'] }),
postcssReporter({ clearMessages: true })
]
}
(and in webpack)
module.exports = {
module: {
rules: [
{
test: /\.css/,
use: [
…
'postcss-loader',
]
}
]
}
}

How to load image by using webpack in .Net MVC

Currently using web pack in .net MVC with Angular 2 development. Hope someone can identify and explain what I have done wrong in the config.
Problem.
Unable to load images (404), check in browser and only 2 images being loaded.
In my project images folder,
webpack.config.js
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /\.(?!js(\?|$))([^.]+(\?|$))/;
// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
resolve: { extensions: [ '', '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
loaders: [
{ test: /\.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
{ test: /\.html$/, loader: 'raw' },
{ test: /\.css$/, loader: 'to-string!css' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
]
}
};
// Configuration for client-side bundle suitable for running in browsers
var clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot-client.ts' },
output: { path: path.join(__dirname, './wwwroot/dist') },
devtool: isDevBuild ? 'inline-source-map' : null,
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
entry: { 'main-server': './ClientApp/boot-server.ts' },
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map',
externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
});
module.exports = [clientBundleConfig, serverBundleConfig];
webpack.config.vendor.js
var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin('vendor.css');
module.exports = {
resolve: {
extensions: ['', '.js']
},
module: {
loaders: [
{ test: /\.(png|jpg|ico|gif|woff|woff2|eot|ttf|svg)(\?|$)/, loader: 'url-loader' },
{ test: /\.css$/, loader: extractCSS.extract("style-loader", "css-loader") }
]
},
entry: {
vendor: [
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'#angular/platform-server',
'angular2-universal',
'angular2-universal-polyfills',
'animate.css/animate.min.css',
'bootstrap',
'bootstrap/dist/css/bootstrap.min.css',
'bootstrap/dist/js/bootstrap.min.js',
'es6-shim',
'es6-promise',
'font-awesome/css/font-awesome.min.css',
'html5shiv',
'isotope-layout',
'jquery',
'wowjs/dist/wow.min.js',
'zone.js',
'./js/main.js',
'./js/respond.min.js',
'./css/main.css',
'./css/prettyPhoto.css',
'./css/responsive.css'
],
},
output: {
path: path.join(__dirname, 'wwwroot', 'dist'),
publicPath: '/',
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
extractCSS,
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
, new CopyWebpackPlugin([{ from: 'images', to: './images' }])
].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
])
};
_Layout.cshtml

Resources