How to resolve #import with Webpack3 - css

I'm trying to add semantic-ui-css to my React application. But, I'm receiving this error message:
"Invalid or unexpected token".
The traceback indicates an issue parsing the #import. Any thoughts or suggestions would be greatly appreciated.
Also, I realize many other people have had this problem, but haven't found a solution on Stack that works yet. Full source is available here: https://github.com/lgants/django-react-ssr.
frontend/webpack.client.base.config.js
var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: './src/client/index.js',
output: {
filename: '[name]-[hash].js',
publicPath: '/static/js/',
path: path.resolve(__dirname, '../backend/app/static/js/')
},
// tells webpack to run babel on every file it runs through
resolve: {
extensions: ['.js', '.jsx', '.json']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
presets: [
'react',
'stage-0',
['env', { targets: { browsers: ['last 2 versions'] } }]
]
}
},
{
test: /\.(png|gif)$/,
loader: 'url-loader?limit=1024&name=[name]-[hash:8].[ext]!image-webpack-loader'
},
{
test: /\.jpg$/,
loader: 'file-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(sass|scss)$/,
loader: ExtractTextPlugin.extract({ use: 'style-loader!css-loader!sass-loader' })
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'less-loader'
]
},
{
test: /\.(ttf|eot|svg|woff2?)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader'
}
]
},
plugins: [
new BundleTracker(
{
filename: './webpack-stats.client.json'
}
),
new CleanWebpackPlugin([
'backend/app/static/js/main-*.*', 'backend/app/static/js/*.hot-update.*'
],
{
dry: false,
root: path.resolve(__dirname, '..'),
watch: true
}
)
]
};
frontend/webpack.client.dev.config.js
var path = require('path');
var merge = require('webpack-merge');
var webpack = require('webpack');
var baseConfig = require('./webpack.client.base.config.js');
var CleanWebpackPlugin = require('clean-webpack-plugin');
const config = {
plugins: [
new webpack.HotModuleReplacementPlugin(),
]
};
module.exports = merge(baseConfig, config);

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

Vue 2 + Webpack: Accessing Assets Folder

I have my assets in the /src/assets/ folder, specifically /src/assets/stylesheets/file.css but I cannot seem to bundle them. In my main.js file I've included the following
require('./assets/stylesheets/file.css')
but it does not work. I see:
Module not found: Error: Can't resolve './assets/stylesheets/codrops.css' in '/Users/USERNAME/Documents/Projects/vue/APPNAME/src'
# ./src/main.js 9:0-43
# multi ./build/dev-client ./src/main.js
I've tried using ../assets and that didn't work either.
Here's my build/webpack.base.conf.js file:
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src')
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}
EDIT: I've updated this file to look like:
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const extractCSS = new ExtractTextPlugin({ filename: 'css.bundle.css' })
const extractSASS = new ExtractTextPlugin({ filename: 'sass.bundle.css' })
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src')
}
},
module: {
// loaders: [
// { test: /\.css$/, loader: "style-loader!css-loader" }
// ],
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.css$/,
use: extractCSS.extract({ // Instance 1
fallback: 'style-loader!css-loader',
use: [ 'css-loader' ]
})
},
{
test: /\.scss$/,
use: extractSASS.extract({ // Instance 2
fallback: 'style-loader',
use: [ 'css-loader', 'sass-loader' ]
})
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
plugins: [
extractCSS,
extractSASS
]
}
but when I require the .css: require("./assets/now-ui-kit.css"); I see the following:
error in ./src/assets/now-ui-kit.css
Module build failed: ModuleBuildError: Module build failed: Unknown word (5:1)
3 | // load the styles
4 | var content = require("!!../../node_modules/css-loader/index.js?{\"minimize\":false,\"sourceMap\":false}!./now-ui-kit.css");
> 5 | if(typeof content === 'string') content = [[module.id, content, '']];
| ^
6 | if(content.locals) module.exports = content.locals;
7 | // add the styles to the DOM
8 | var update = require("!../../node_modules/vue-style-loader/lib/addStylesClient.js")("94a1c16e", content, false);
It doesn't look like you have any css loader in your webpack config file. Add the following imports, rules and plugins to your file to accomplish the css bundling:
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const extractCSS = new ExtractTextPlugin({ filename: 'css.bundle.css' })
const extractSASS = new ExtractTextPlugin({ filename: 'sass.bundle.css' })
const config = {
module: {
rules: [
{
test: /\.css$/,
use: extractCSS.extract({ // Instance 1
fallback: 'style-loader',
use: [ 'css-loader' ]
})
},
{
test: /\.scss$/,
use: extractSASS.extract({ // Instance 2
fallback: 'style-loader',
use: [ 'css-loader', 'sass-loader' ]
})
}
]
},
plugins: [
extractCSS // Instance 1
extractSASS // Instance 2
]
}
Here is where I took the code snippet from and here is the webpack css documentation.

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 sperates the less file in a css file with webpack 2?

I can compile the less on the page within the <style></style> by webpack2. but I can't compile the less file into a CSS file.
webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var ENV = process.env.NODE_ENV;
var port = '10101';
var commonAttr = ['common', 'markerFactory', 'sceneTransform', 'sparFactory', 'upload'];
var vendorArr = [];
for (var i = 0, l = commonAttr.length; i < l; i++) {
vendorArr.push(path.resolve(__dirname + '/script/common/', commonAttr[i] + '.js'))
}
var config = {
entry: {
vendor: vendorArr,
app: './script/app',
},
output: {
path: path.resolve(__dirname, 'wds'),
filename: '[name].bundle.js',
publicPath: '/wds/'
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
// // this option will compile the less to css, and append style tag to the page
{
test: /\.less$/,
use: [
"style-loader",
"css-loader",
"less-loader"
]
},
// I tried to split the css file into a indenpendent file, but it didn't work
{
test: /\.less$/,
use: {
loader: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: "css-loader!less-loader",
})
}
},
{
test: /\.html$/,
use: "handlebars-loader?helperDirs[]=" + __dirname + "/script/helpers"
}]
},
plugins: [
new ExtractTextPlugin('[name].bundle.css'),
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
filename: "vendor.js"
})
],
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
devServer: {
compress: true,
// hot: true,
publicPath: '/wds/', //可访问的路径地址
port: port
}
}
if (ENV == 'development') {
config.devtool = 'inline-source-map'; // 将模块单独编译 成 单个文件 浏览器可调试
}
else {
config.devtool = 'eval-source-map'; // 将模块压缩一个文件一行 打包进bundle
}
var compiler = webpack(config);
module.exports = config;
But it gives the following errors:
If I don't use the ExtractTextPlugin in rules use loader, it can compile to style tag. Where is this going wrong?
Sorry, I fixed it!
define:
var extractLESS = new ExtractTextPlugin('[name].bundle.css');
module:
rules:[{
test: /\.less$/,
use: extractLESS.extract([ 'css-loader', 'less-loader' ])
}]
plugin:
plugins: [
extractLESS,
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
filename: "vendor.js"
})
],

How to set material-css with webpack config?

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'

Resources