How to set material-css with webpack config? - css

Sorry to bother, because it could be a local problem. But it has been bothering me for days.
Here is my webpack config:
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: 'dist/',
filename: 'build.js'
},
resolveLoader: {
root: path.join(__dirname, 'node_modules'),
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel?{"presets":["es2015"]}',
exclude: /node_modules/
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
"style-loader", "css-loader?sourceMap!postcss-loader")
},
{
test: /\.(jpg|png|gif)$/,
loader: "file-loader?name=images/[hash].[ext]"
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000&minetype=application/font-woff"
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader"
}
]
},
vue: {
loaders: {
css: ExtractTextPlugin.extract("css"),
}
},
plugins: [
new ExtractTextPlugin("style.css", {
allChunks: true,
disable: false
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
})
],
devtool: '#eval-source-map'
}
and my main.js:
import './libs/materialize/js/materialize.js'
import './libs/materialize/css/materialize.css'
Everything is fine, but when I check out the console of Chrome, it tells me this:
localhost/:13 GET http://localhost:3000/dist/dist/2751ee43015f9884c3642f103b7f70c9.woff2
localhost/:13 GET http://localhost:3000/dist/dist/ba3dcd8903e3d0af5de7792777f8ae0d.woff
localhost/:13 GET http://localhost:3000/dist/dist/df7b648ce5356ea1ebce435b3459fd60.ttf
Can you guys help me for this? Big thanks.

You must import define like this.
import 'materialize-css/dist/js/materialize.min.js'
import 'materialize-css/dist/css/materialize.min.css'

Related

Rearrange style order in ccs bundle

After a migration from grunt, the styles are not working as intended with webpack. All the styles were concatenated in the gruntfile like this:
target: {
files: {
"all.css": [
"node_modules/bootstrap/dist/css/bootstrap.css",
"bower_components/toastr/toastr.css",
"bower_components/angular-ui-select/dist/select.css",
"node_modules/font-awesome/font-awesome.css",
"bower_components/angular-loading-bar/build/loading-bar.css",
"bower_components/angular-ui-tree/dist/angular-ui-tree.css",
"content/styles/awesome-bootstrap-checkbox.css",
"content/styles/tradesolution.css",
"content/styles/site.css",
"content/styles/ts.css",
"content/styles/nyKladd.css"
]
}
}
My current config in webpack:
var webpack = require('webpack');
var globby = require('globby');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var AssetsPlugin = require('assets-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
const ConcatPlugin = require('webpack-concat-plugin');
const extractCSS = new ExtractTextPlugin('[name].css');
const extractLESS = new ExtractTextPlugin('[name].css');
module.exports = {
entry: {
app: globby.sync(['./app/app.js','./app/app.run.js', './app/app.config.js', './app/**/*.js']),
Ztyles: globby.sync(['./content/styles/less/*.less']),
styles: globby.sync(['./content/styles/*.css']),
images: globby.sync(['./content/images/**/*.*']),
vendor: [
// removed to save space
],
},
output: {
filename: './scripts/[name].bundle.js',
path: path.join(__dirname, "public")
},
devServer: {
port: 1384,
contentBase: './public/'
},
// Enable sourcemaps for debugging webpack's output.
devtool: (() => {
if(NODE_ENV = "devlopment") return 'source-map'
else return 'cheap-module-eval-source-map'
}) (),
module: {
rules: [
{
test: /\.html$/,
loader: 'raw-loader',
exclude: [/node_modules/]
},
{
test: /\.css$/,
loader: extractCSS.extract(
{ fallback: 'style-loader', use: 'css-loader' }
),
//'style-loader', 'css-loader'
},
{ test: /\.less$/,
use: extractLESS.extract(
{fallback:'style-loader', use: ['css-loader','less-loader']}
)
//'style-loader', 'css-loader!less-loader'
},
{
test: /\.(ico)$/,
loader: "url-loader?name=./[name].[ext]",
include: path.resolve(__dirname, "content", "images")
},
{
test: /\.(jpg|jpeg|gif|png|PNG|tiff|svg)$/,
loader: 'file-loader?name=/[path]/[name].[ext]',
include: path.resolve(__dirname, "content", "images"),
},
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&minetype=application/font-woff&name=./fonts/[name].[ext]' },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader?name=./fonts/[name].[ext]' },
{
test: require.resolve('adal-angular/lib/adal'),
loader: 'expose-loader?AuthenticationContext'
},
{
test: /\.js$/,
enforce: "pre",
loader: 'source-map-loader'
}
],
},
plugins: [
new webpack.DefinePlugin({
ADMIN_API_URL: JSON.stringify('http://localhost:41118/api/'),
API_URL: JSON.stringify('http://epdapi.tradesolution.no/'),
GLOBAL_ADMIN_URL: JSON.stringify('https://adminapi.tradesolution.no/')
}),
new HtmlWebpackPlugin({
template: './app/layout.html',
filename: 'index.html'
}),
extractCSS,
extractLESS,
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: './scripts/vendor.bundle.js' }),
new ExtractTextPlugin({ filename: './[name].bundle.css' }),
new AssetsPlugin({
filename: 'webpack.assets.json',
path: './public',
prettyPrint: true
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
"window.AuthenticationContext": "AuthenticationContext",
_: 'underscore'
}),
new CopyWebpackPlugin([
{from: './app/**/*.html', to: './'}
]),
new DashboardPlugin()
],
externals: [
{ xmlhttprequest: '{XMLHttpRequest:XMLHttpRequest}' }
],
}
From this picture you can see that the default bootstrap styles are overriding the styles written for the nav-bar.
What i have done so far is to implement all the other css files into one less file, like this:
#import "../tradesolution.css";
#import "../site.css";
#import "../nykladd.css";
#import "for";
#import "kladd.less";
#import "~bootstrap/less/bootstrap";
#import "~bootstrap/less/alerts.less";
#import "~bootstrap/less/mixins/buttons.less";
#import "~font-awesome/less/font-awesome.less";
Then the less file is compiled to css and loaded in the Ztyles.css , but regardless of where I put the imports, my styles are still overridden. I have also tried changing the order of the webpack rules and the order of extractCSS and extractLESS in plugins
I dont think my intended solution is good practice, so any approach to solving this issue is very welcome.
After a while i stumbled over a new css framework postcss they have all kinds of plugins, and with this configuration I got it to work:
{
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { modules: true, importLoaders: 1 },
loader: 'postcss-loader',
},
]
},
{ test: /\.less$/,
use: extractLESS.extract(
{fallback:'style-loader', use: ['css-loader', 'less-loader']}
)
},
Here are some resources that helped:
https://github.com/postcss/postcss
https://webdesign.tutsplus.com/tutorials/using-postcss-together-with-sass-stylus-or-less--cms-24591
https://github.com/Crunch/postcss-less

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',
]

WebPack bundling breaks CSS

We have recently moved from Browserify to WebPack, while it has many nice plugins and optimisations, our (not so clean CSS) started to break.
I tracked the reason to a <style> block somehow inserted into the document.
A screenshot is attached, how to solve this?
Here is our webpack.conf.json
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
var BundleTracker = require('webpack-bundle-tracker');
module.exports = {
context: __dirname,
module: {
loaders: [{
loader: "babel-loader",
include: [
path.resolve(__dirname, "static/js")
],
test: /\.js?$/,
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'stage-0', 'react']
}
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
}, {
test: /\.(png|jpg|svg)?(\?v=\d+.\d+.\d+)?$/,
loader: 'url-loader?limit=8192'
}, {
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff'
}, {
test: /\.(ttf|otf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?|(jpg|gif)$/,
loader: 'file-loader'
}]
},
output: {
path: path.resolve('./static/bundles/'),
filename: "bundle.js"
},
plugins: [
new BundleTracker({
filename: './webpack-stats.json'
}),
new ExtractTextPlugin('bundle.css'),
new OptimizeCssAssetsPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
NProgress: 'nprogress',
toastr: 'toastr',
Cookies: 'js-cookie',
moment: 'moment'
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
minimize: true,
compress: true,
compressor: {
warnings: true
}
})
],
entry: [
// npm js
'./node_modules/select2/dist/js/select2.full.js',
'./node_modules/jquery-ticker/jquery.ticker.js',
'./node_modules/card/dist/jquery.card.js',
'./node_modules/jquery-ui/ui/widgets/datepicker.js',
'./node_modules/js-cookie/src/js.cookie.js',
'./node_modules/moment-timezone/builds/moment-timezone-with-data.js',
'./node_modules/intl-tel-input/build/js/intlTelInput.js',
'./node_modules/bootstrap-toggle/js/bootstrap-toggle.min.js',
// loader
'bootstrap-loader',
// run package
'./static/run.js',
// old javascript
'./static/js/profile.js',
'./static/js/main.js',
'./static/js/index_orders.js',
'./static/js/footer.js',
'./static/js/django_jquery_csrf_setup.js'
]
};

How to get svg from MDL working with webpack

Using a checkbox component form Material Design Lite, i.e.
https://getmdl.io/components/index.html#toggles-section/checkbox
the tickmark.svg is not shown properly when I use
import '../../node_modules/material-design-lite/src/material-design-lite.scss';
for bundling with npm and webpack. Instead of:
I get:
In the browser I find the following path to tickmark.svg which is the svg that is 'missing':
When using either one of these two alternatives it works as it should:
1) import '../../node_modules/material-design-lite/.tmp/material-design-lite.css';
2) import '../../node_modules/material-design-lite/material.min.css';
To compare, when using 2 I get following in the browser:
My webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var Clean = require('clean-webpack-plugin');
var bootstrapPath = path.join(__dirname, 'node_modules/bootstrap/dist/css');
var sourcePath = path.join(__dirname, 'assets');
module.exports = {
devtool: 'eval-source-map',
context: __dirname,
entry: [
'./assets/js/index' // entry point of our app. .assets/js/index.js should require other js modules and dependencies it needs
],
output: {
path: path.resolve('./assets/bundles/'),
filename: '[name]-[hash].js',
}
,
node: {
console: true,
fs: 'empty'
}
,
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new BundleTracker({filename: './webpack-stats.json'}),
new webpack.BannerPlugin('Pqbq Banner!!!! todo'),
new HtmlWebpackPlugin({
template: __dirname + '/assets/index.tmpl.html'
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new Clean(['assets/bundles'])
],
module: {
preloaders: [
{
test: /\.js/,
loader: 'eslint'
}
],
loaders: [
{
test: /\.js[x]?$/,
loader: 'babel',
exclude: /(node_modules|bower-components)/,
query: {
presets: ['es2015', 'stage-0']
}
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.js$/,
include: path.resolve(__dirname, 'node_modules/mapbox-gl/js/render/shaders.js'),
loader: 'transform/cacheable?brfs'
},
{
test: /\.js$/,
include: path.resolve(__dirname, 'node_modules/webworkify/index.js'),
loader: 'worker'
},
// {
// test: /\.css$/,
// loader: 'style!css?modules!postcss'
// },
{
test: /\.scss$/,
loaders: ['style', 'css?sourceMap', 'sass?sourceMap']
},
// {test: /\.(woff2?|svg)$/, loader: 'url?limit=10000'},
// {test: /\.(ttf|eot)$/, loader: 'file'},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
{test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
// {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
{test: /\.svg$/, loader: 'url?limit=8192!svgo'},
]
}
,
postcss: [
require('autoprefixer')
],
resolve: {
modulesDirectories: ['node_modules', 'bower_components', bootstrapPath, sourcePath],
extensions: ['', '.js', '.jsx', '.css'],
alias: {
webworkify: 'webworkify-webpack',
'$': 'jquery',
'jQuery': 'jquery'
}
}
,
devServer: {
contentBase: './assets',
colors: true,
historyApiFallback: true,
inline: true,
hot: true
}
};
To fix this I had to override the $image_path variable by creating my own material.scss file. I grabbed this file:
https://github.com/google/material-design-lite/blob/master/src/material-design-lite.scss
and then added:
#import "./variables";
at the top.
In that file I added this line:
$image_path: '~material-design-lite/dist/images/' !default;

Webpack style-loader modules are overriding installed component css

I am using the react-super-select component in a react/redux project that I'm working on.
That project currently uses webpack and style-loader to load my styling:
const path = require('path');
const webpack = require('webpack');
const poststylus = require('poststylus');
module.exports = {
entry: [
'webpack-hot-middleware/client',
'./src/client/index',
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff',
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
},
{
test: /\.styl$/,
loader: 'style-loader!css-loader?modules!stylus-loader',
}],
},
stylus: {
use: [
poststylus([ 'autoprefixer', 'rucksack-css' ]),
],
},
};
I am finding that this use of style-loader seems to be overriding the styling provided with react-super-select.
Is there a way to configure webpack so that it does not override the style for this component?
Ok, I figured out how to do this -- I created a wrapper component that loaded the css explicitly:
import React, { PropTypes, Component } from 'react';
import ReactSuperSelect from 'react-super-select';
import 'react-super-select/lib/react-super-select.css';
export default class Dropdown extends Component {
render() {
const { options, onChange, ...preferences } = this.props;
return (
<ReactSuperSelect placeholder={preferences.placeholder}
dataSource={options}
onChange={onChange}
searchable={preferences.searchable} />
);
}
}
Dropdown.propTypes = {
options: PropTypes.array.isRequired,
onChange: PropTypes.func.isRequired,
preferences: PropTypes.object.isRequired,
};
and then I added a line to load css in my webpack config:
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url?limit=10000&mimetype=application/font-woff',
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file',
},
{
test: /\.styl$/,
loader: 'style!css?modules!stylus',
},
{
test: /\.css$/,
loader: 'style!css',
}],
},

Resources