Webpack 2: how to test for file but not compile it? - javascript

I'm requiring a bunch of .css files from my npm modules in my main.js file which is the entry point of my webpack config, as you can see here:
"use strict";
const ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require("webpack");
module.exports = {
entry: {
dashboard: './js/main.js',
vendor: ["fixed-data-table","react","react-dom","jquery", "bootstrap"],
},
output: { path: "../resources/public", filename: 'bundle.js' },
plugins: [
new webpack.optimize.CommonsChunkPlugin({name: "vendor", filename: "static/vendor.bundle.js"}),
new ExtractTextPlugin("[name].css"),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
],
module: {
loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react', 'stage-0']
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader'}),
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file-loader',
],
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
},
};
If I do not test for fonts and images, i will get errors building since some modules, for example bootstrap.css, will look for .png and various fonts.
So I added the loaders for testing images and fonts, which now works: It will build!
However, it also processes and outputs a bunch of .png, .woff2, .eot, .tff files to the same output folder which I don't want.
A "dirty fix" would be to make a .sh script where I just delete these specific files after running webpack in the terminal. But I'd rather not do that.
How can I change my webpack config to test for images and fonts, but not process and output them to the output folder?

The "dirty" solution is simply to output those files to the trash as such:
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file-loader?hash=sha512&digest=hex&name=~/.local/share/Trash/[hash].[ext]',
'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
],
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader?name=~/.local/share/Trash/[name].[ext]'
}
It works but it surely shouldn't be done this way :)

{ test: /\.jpg$/, loader: "file-loader?name=assets/images/[hash].[name].[ext]"},
{ test: /\.png$/, loader: "file-loader?name=assets/images/[hash].[name].[ext]&mimetype=image/png"},
{
test: /\.(html|hbs)$/,
loaders: ['handlebars-template-loader']
},
// Bootstrap 4
// { test: /bootstrap\/dist\/js\/umd\//, loader: 'imports?jQuery=jquery' },
// Bootstrap 3
// { test: /bootstrap-sass\/assets\/javascripts\//, loader: 'imports?jQuery=jquery' },
{
test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url?name=assets/fonts/[hash].[name].[ext]&limit=10000',
},
{ test: /\.[ot]tf$/, loader: 'url?limit=65000&mimetype=application/octet-stream&name=assets/fonts/[name].[ext]' },
{
test: /\.(eot|svg)(\?[\s\S]+)?$/,
loader: 'file?name=assets/fonts/[hash].[name].[ext]',
}

Related

Webpack won't compile my SASS with background-image

I have issue compiling my SASS code.
I would like to use a background image, but when I tried this, all my css stopped working.
My SASS file looks like this
#import "~bootstrap/scss/bootstrap";
#import "constants";
#crossroad {
position:relative;
background-image: url("../assets/bg.jpg");
}
My Webpack.config
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: "development",
module: {
rules: [
{
test: /\.(scss|png|jpg)$/,
use: [
{
// Adds CSS to the DOM by injecting a `<style>` tag
loader: 'style-loader'
},
{
// Interprets `#import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader'
},
{
// Loader for webpack to process CSS with PostCSS
loader: 'postcss-loader',
options: {
plugins: function () {
return [
require('autoprefixer')
];
}
}
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'resolve-url-loader'
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'sass-loader'
}
]
}
]
}
};
ERROR MESSAGE:
ERROR in ./src/assets/bg.jpg (./node_modules/css-loader/dist/cjs.js!./node_modules /postcss-loader/src??ref--4-2!./node_modules/resolve-url-loader!./node_modules/sass-loader/dist/cjs.js!./src/assets/bg.jpg)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Invalid CSS after "����": expected "{", was ""
on line 1 of /Users/adrianmindek/Code/PersonalPage/src/assets/bg.jpg
����
^
# ./src/assets/bg.jpg 2:26-236
# ./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/src??ref-- 4-2!./node_modules/resolve-url-loader!./node_modules/sass-loader/dist/cjs.js!./src/scss/app.scss
# ./src/scss/app.scss
# ./src/app.js
I tried to add resolve-url-loader to my webpack config, but nothing changed.
You should handle file using file-loader like this
rules: [{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: ["babel-loader", "eslint-loader"]
},
{
test: /\.(jpe?g|png|gif)$/i,
loader: "file-loader"
},
{
test: /\.(woff|ttf|otf|eot|woff2|svg)$/i,
loader: "file-loader"
}
]
You can view code from here

Unexpected token given when loading import() with Webpack 4.24.0 or higher

I've been on a dependencies upgrade mission and I have found when upgrading Webpack to 4.24.0 or above I get this failure:
ERROR in ./src/js/components/App.jsx 35:9
Module parse failed: Unexpected token (35:9)
You may need an appropriate loader to handle this file type.
| import ReactModal from 'react-modal';
| var RoomListings = React.lazy(function () {
> return import('./RoomListings.jsx');
| });
| var RoomDetails = React.lazy(function () {
# ./src/js/index.js 3:0-39 6:74-77
# multi ./src/js/index.js
It's failing on the import but what is frustrating is that nothing has changed in either my Webpack or Babel config which are below:
webpack.config.js
module.exports = {
entry: ["./src/js/index.js"],
output: {
path: PATHS.build,
filename: "js/[name].js"
},
devServer: {
contentBase: path.join(__dirname, 'src'),
publicPath: '/'
},
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"},
{ test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.html$/, loader: "html-loader" },
{ test: /\.css$/, use: ['style-loader', 'css-loader'] },
{ test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] },
{ test: /\.(png|jp(e*)g|svg)$/, use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
.babelrc
{
"presets": ["#babel/env", "#babel/react"],
"plugins": ["add-react-displayname", "#babel/plugin-syntax-dynamic-import", "emotion"],
"env": {
"test": {
"plugins": ["dynamic-import-node"]
}
}
}
I am assuming something is either missing or misconfigured, but after hours of searching SO and Google, none of the existing answer appear to help.

Compile scss with webpack for an Angular App

I'm using webpack 3 for my angular app. I have some issues with compiling my scss files. Here is full webpack config file:
const path = require('path')
const autoprefixer = require('autoprefixer')
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const config = {
context: __dirname + '/src',
entry: {
app: './index.js',
vendor: [
'angular',
'angular-animate',
'angular-bootstrap',
'angular-route',
'animate',
'bootstrap',
'bootstrap-filestyle',
'jquery',
'ng-file-upload',
'ng-parallax'
]
},
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'app'),
publicPath: path.join(__dirname, 'app')
},
resolve: {
extensions: ['.js', '.jsx', '.scss']
},
module: {
loaders: [
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader',
'css?minimize!postcss!sass')
},
{
test: /\.(eot|woff|woff2|ttf|svg)(\?\S*)?$/,
loader: 'file?name=fonts/[name].[ext]'
},
{
test: /\.(jpg|jpeg|gif|png|svg)$/,
loader: 'file?name=images/[name].[ext]'
}
],
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.svg$/,
loader: 'url-loader'
},
{
test: /\.php$/,
loader: 'file-loader?name=[name].[ext]'
},
{
test: /\.zip$/,
loader: 'file-loader?name=[name].[ext]'
},
{
test: /(\.png|\.jpg|\.gif)$/,
loader: 'file-loader?name=[path][name].[ext]'
}
]
},
plugins: [
new ExtractTextPlugin('./bundle.css'),
new CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.bundle.js'
}),
new UglifyJSPlugin({})
// new ExtractTextPlugin({
// filename: '[name].min.css'
// })
]
}
module.exports = config
After running webpack i've got this error:
ERROR in ./assets/sass/main.scss
Module parse failed: /home/git/project/src/public/src/assets/sass/main.scss Unexpected token (1:13)
You may need an appropriate loader to handle this file type.
| $header-color: #ffffff;
| $admin-panel-height: 40px;
|
# ./index.js 3:0-34
Also i tried to use this loader: https://github.com/webpack-contrib/sass-loader
After webpack build there no errors appeared, but css file also was not created in /app folder.
file main.scss imports in index.js:
import './assets/sass/main.scss'
Can anyone give me an advice how can i build and watch scss files with webpack 3 ?
You have used some of the loader configs that suppose to be for webpack 1.
That section of the config:
loaders: [
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader',
'css?minimize!postcss!sass')
},
{
test: /\.(eot|woff|woff2|ttf|svg)(\?\S*)?$/,
loader: 'file?name=fonts/[name].[ext]'
},
{
test: /\.(jpg|jpeg|gif|png|svg)$/,
loader: 'file?name=images/[name].[ext]'
}
],
There are breaking changes when you move to Webpack 2 (or 3).
One of them was module.loaders => module.rules.
You will need to convert that section to the new structure.
In addition, ExtractTextPlugin changes it config style as well, please read it README.

webpack + babel - react, unexpected token 'import'

I'm trying to make index.js work with es2015.
Before directing me to .babelrc, note that I have added BOTH es2015 and react (to be sure, but there's no react here).
It features
import { default as Logary, Targets, getLogger, build } from 'logary';
And here's .babelrc:
{
"presets": ['es2015', 'react']
}
And webpack.config.js
var webpack = require('webpack'),
HtmlWebpackPlugin = require('html-webpack-plugin'),
path = require('path');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client?reload=true',
'./index.js'
],
output: {
path: path.resolve('./dist'),
filename: '[name].js',
publicPath: '/'
},
loaders: [
{ test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{ test: /\.css$/, loader: "style!css" },
{ test: /\.(png|jpg|jpeg|gif|woff)$/, loader: 'url?limit=8192' },
{ test: /\.(otf|eot|ttf)$/, loader: "file?prefix=font/" },
{ test: /\.svg$/, loader: "file" }
],
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.template.html'
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
resolve: {
extensions: ['', '.js']
}
}
Gives error:
ERROR in ./index.js
Module parse failed: /Users/h/logary-js/examples/webpack/index.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import { default as Logary, Targets, getLogger, build } from 'logary';
|
| // once per site/app
Why is it not handling the import-token?
Your webpack.config.js structure is not correct. Webpack doesn't recognize all your loaders. Specifically, you need to put the loaders property inside of a module section like this:
module: {
loaders: [
{ test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{ test: /\.css$/, loader: "style!css" },
{ test: /\.(png|jpg|jpeg|gif|woff)$/, loader: 'url?limit=8192' },
{ test: /\.(otf|eot|ttf)$/, loader: "file?prefix=font/" },
{ test: /\.svg$/, loader: "file" }
],
}

Use webpack with jade-loader without explicitly requiring assets

I am trying to use Webpack jade-loader in combination with html-loader to be able to omit requires in jade templates + use a path relative to a certain folder. I have tried a few things, none of them worked.
By default jade-loader works when using img(src=require("../../../../assets/images/imac.png") alt="computer"), with the following webpack config:
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/app.js'
],
context: path.resolve(__dirname + "/client"),
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
// placed here so we know that it is done before transpiling
preLoaders: [
{ test: /\.js$/, loader: "eslint-loader", exclude: [/node_modules/, /\.config\.js/, /\.conf\.js/ ] }
],
loaders: [
{ test: /\.html$/, loader: 'raw' },
{ test: /\.jade$/, loader: 'jade-loader' },
{ test: /\.less$/, loader: 'style!css!less' },
{ test: /\.css/, loader: 'style!css' },
{ test: /\.(png|jpg|jpeg|svg)$/, loader: 'file' },
{ test: /\.js$/, loader: 'babel?stage=1', exclude: [/client\/lib/, /node_modules/, /\.spec\.js/] }
]
},
eslint: {
configFile: './.eslintrc'
}
};
If I add the html-loader ({ test: /\.jade$/, loader: 'html-loader!jade-loader' }) which is supposed to require sources by default, I keep getting the 'Error: Module not found'. The console logs all the paths that it tried, all relative to the current working file.
I tried to give it some context, with context: path.resolve(__dirname + "/client"). It didn't work either.
I also tried to combine with the raw loader: raw-loader!html-loader!jade-loader. I don't get the error but the wepback output that is served is not my app at all, but instead something along the lines of:
var jade = require(/......) ....
Do you have any idea ?
Thanks for your help
Had the same Problem.
https://www.npmjs.com/package/pug-html-loader worked for me:
module.exports = {
// your config settings ...
module: [
//your modules...
loaders: [{
include: /\.jade/,
loader: 'pug-html-loader'
}]
]
};
I don't know what do you want. My need is to load a template from a directive (component in 1.5)
angular.module('app').component('myComponent', {
bindings: {},
template: require('./mytemplate.jade')()
});
You can to note that I'm invoking the returned function.

Categories