I have a few JS and SCSS files. I need Webpack 4 to bundle each JS entry to one JS file and each SCSS entry to one CSS file. The JS files don't import the SCSS files. I try to do it with the following webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: {
scriptFoo: './src/js/scriptFoo.js',
scriptBar: './src/js/scriptBar.js',
// ...
styleBaz: './src/css/styleBaz.scss',
styleBaq: './src/css/styleBaq.scss'
// ...
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.(scss|sass)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css'
})
]
};
It works fine, Webpack puts the compiled files to the dist directory. But it also creates an excess dummy JS file for each SCSS file in the dist directory:
webpack.config.js
src/
js/
scriptFoo.js
scriptBar.js
...
css/
styleBaz.scss
styleBaq.scss
...
dist/
scriptFoo.js
scriptBar.js
...
styleBaz.css
styleBaz.js // Excess
styleBaq.css
styleBaq.js // Excess
...
How to make Webpack not to create the excess JS files?
Use the ignore-emit-webpack-plugin Webpack plugin to not create the excess file. First install it by running in a console:
npm install --save-dev ignore-emit-webpack-plugin
Then add it to your Webpack configuration:
const IgnoreEmitPlugin = require('ignore-emit-webpack-plugin');
module.exports = {
// ...
plugins: [
// ...
new IgnoreEmitPlugin(['styleBaz.js', 'styleBaq.js']) // Or simply: new IgnoreEmitPlugin(/^style.*\.js$/)
]
};
It is because for each property in the entry object ,The js file is created in output destinations.
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
Webpack creating dummy js when css is an entry point is a known bug, which has not been fixed yet.
Also having multiple entry files in the entry configuration will also affect treeshaking capabilties
Related
In webpack it is possible to generate output in such a way:
1 file with bundled js code
1 file with bundled css
This is part of the webpack config, that results in such output:
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
...
plugins: [
new MiniCssExtractPlugin({
filename: 'assets/css/styles.css',
chunkFilename: '[id].css',
}),
...
],
...
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
},
],
},
...
How to achieve this with vite?
The vite templates by default generate config, where js and css are bundled into a single file and css is injected at runtime.
Here is my webpack.config (using webpack 3) below
I have several .js files in entry.
I'd like to find a way to transpile select .js files through babel while excluding others.
I found a way to include all the .js files in the js/ directory through babel.. But how can I exclude the .js files in js/vendor?
const path = require('path');
const webpack = require('webpack');
module.exports = {
context: __dirname,
entry: {
dataviz : '../js/entry-dataviz.js',
template : '../js/entry-viz-template.js',
abc : '../js/entry-viz-abc.js',
sample: '../js/sample.js',
vendor: [
'../js/vendor/bootstrap.min.js',
'../js/vendor/history.js',
'../js/vendor/history.adapter.jquery.js'
]
},
output: {
filename: '[name]-[chunkhash].js'
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, '../js'), <-- including everything in js/directory
],
use: {
loader: 'babel-loader',
options: { presets: 'es2015'}
}
}
]
},
include can accept a function:
include: function (modulePath) {
// inside `js` folder but not `js/vendor`
return true;
}
I'm a newbie to webpack and I'm having trouble understanding how I can take a bunch of scss files and css files and merge them together with webpack (After transpiling the sass of course).
With gulp, it was really obvious, as I can have 1 step the transpile the sass to css and then a step after that to concatenate them together.
However with webpack, it looks like everything happens at the same time.
This is a pretty basic requirement that I'm sure has an obvious answer to those more experienced.
I've got to the point where I can successfully output a transpiled scss to css and seperately output a css file from css input, but I can't figure out how to stick them together using webpack.
Below is my webpack.config.js file:
const path = require('path');
const webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSS = new ExtractTextPlugin('extractedCSS.css');
const extractSass = new ExtractTextPlugin({
filename: "extractedSASS.css",
disable: process.env.NODE_ENV === "development"
});
module.exports = function (env) {
return {
context: path.resolve(__dirname, './wwwroot/app'),
entry: {
main: './index.js',
vendor: 'moment'
},
output: {
filename: '[name].[chunkhash].js',
path: path.resolve(__dirname, './wwwroot/mytempdist')
},
module: {
rules: [{
test: /\.css$/,
use: extractCSS.extract({
use: 'css-loader'
})
},
{
test: /\.scss$/,
use: extractSass.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}],
// use style-loader in development
fallback: "style-loader"
})
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module) {
// this assumes your vendor imports exist in the node_modules directory
return module.context && module.context.indexOf('node_modules') !== -1;
}
}),
//CommonChunksPlugin will now extract all the common modules from vendor and main bundles
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest' //But since there are no more common modules between them we end up with just the runtime code included in the manifest file
}),
//new webpack.optimize.UglifyJsPlugin({
// sourceMap: options.devtool && (options.devtool.indexOf("sourcemap") >= 0 || options.devtool.indexOf("source-map") >= 0)
//}),
extractSass,
extractCSS
],
devtool: 'inline-source-map'
}
}
How can I modify the above to make both the sass and css go into the file css output file?
Incase it makes a difference, below is an exerpt from my index.js file (entry point) toastr is an npm package and pace is just a normal downloaded css file:
var toastr = require('toastr');
import 'toastr/toastr.scss';
import pace from './../lib/pace/pace.min.js';
import './../lib/pace/pace.css';
You have 2 instances of ExtractTextPlugin defined with explicit names and you use those separate instances to load css and scss files respectively.
What you need is only 1 instance of the plugin which will accumulate all the CSS and only one rule for both scss and css files.
{
test: /\.s?css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
This will handle both scss and css files and put it all in one single output CSS file.
I'd like to have structure like this
-Styles
--Main.scss
--SomeComponent.scss
-CompiledStyles
--Main.css
--SomeComponent.css
Actually I can only do this
-Styles
--Main.scss
--SomeComponent.scss
--All.scss (import all scss from file)
-CompiledStyles
--Main.css ( all css)
This is my webpack config
var Path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS2 = new ExtractTextPlugin('[name].css');
module.exports = {
devtool: 'eval',
entry: './Client/Styles/All.scss',
output: {
path: Path.join(__dirname, 'CompiledStyles'),
filename: 'page.js',
publicPath: '/CompiledStyles/'
},
module: {
loaders: [
{
test: /\.scss$/,
loader: extractCSS2.extract("style-loader", "css-loader!autoprefixer-loader!sass-loader")
},
{
//IMAGE LOADER
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader'
},
{
test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader?name=fonts/[name].[ext]'
}
]
},
plugins: [
extractCSS2
]
};
Is it possible to compile this scss files to single css files ?
I really don't know how to manage this case. I've tried to assign entry: './Client/Styles' but it occures error.
EDIT:
I solved this with gulp.
The idea of webpack is to put everything that is needed in some JavaScript-files. So it's the intention to not build a css-file for every css-file.
If you want to still use webpack, try this in your webpack config:
module.exports = {
// ...
entry: {
'Main': './Client/Styles/Main.scss',
'SomeComponents': './Client/Styles/SomeComponents.scss',
},
// ...
}
I have updated the answer after adamo94 noted that he used gulp, so just for everybody else some more information. To convert scss files you need a sass/scss-processor. You can easily call that processor with a single call but as you usually do more with your sources it's likely to use some further processing.
Usually you would use gulp or grunt. Those can be configured to build everything that you need. They have different pros and cons, there are also further tools, but those are probably the ones that you'd like to take a look.
I need to inject a Stylus bundle into the html file in webpack config file.
I already inject the js bundle using HtmlWebpackPlugin and I thought that it was possible to inject a compiled stylus bundle using this plugin too.
Below is my current webpack.config.js file:
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackPluginConfigForJS = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
var HtmlWebpackPluginConfigForStyles = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.styl',
inject: 'head'
});
module.exports = {
entry: [
'babel-polyfill',
'./app/index.js'
],
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
devtool: 'source-map',
cache: true,
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader'
},
{
test: /\.styl$/,
exclude: /(node_modules|bower_components)/,
loader: 'style-loader!css-loader!stylus-loader'
}
]
},
plugins: [
HtmlWebpackPluginConfigForJS,
HtmlWebpackPluginConfigForStyles
],
stylus: {
use: [require('nib')(), require('rupture')()],
import: ['~nib/lib/nib/index.styl', '~rupture/rupture/index.styl']
}
}
The only way I got the styles work was to add require('./index.styl); in my javascript file, but this is not what I need.
HtmlWebpackPluginConfigForJS works fine and successfuly injects the index_bundle.js file in my index.html. But it doesn't work with the styles.
Could you please help me to improve my webpack config to make it inject my stylus bundle correctly?
By default HtmlWebpackPlugin injects css files, from the docs:
If you have any css assets in webpack's output (for example, css extracted with the ExtractTextPlugin) then these will be included with tags in the HTML head.
So you can use ExtractTextPlugin to extract all your styles into one or several files. But to extract you should require your index.styl in your main index.js so that loader could see and make extraction.