minify with raw bundler plugin in webpack - javascript

Objective is to concatenate src files to create a library file, and then create another version that's minified with sources maps. I'm using RawBundlerPlugin.
Following works like a charm! What's missing is how to generate another minified library.
const path = require("path");
const RawBundlerPlugin = require("webpack-raw-bundler");
module.exports = {
entry: "./src/header.txt",
output: {
filename: "MyLib.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{ test: /\.txt$/, use: "raw-loader" }
]
},
plugins: [
new RawBundlerPlugin({
readEncoding: "utf-8",
bundles: [ "MyLib.js" ],
"MyLib.js": [
"src/header.txt",
"src/Product.js",
"src/Customer.js",
"src/copyright.txt"
]
})
],
mode: "none"
};
Question: How to include a minification build with sources maps using above configuration?
Or
maybe take the dist/MyLib.js and minify it to dist/MyLib.min.js through a subsequent process.
attempt https://webpack.js.org/plugins/uglifyjs-webpack-plugin/
optimization: {
minimizer: [new UglifyJsPlugin({
test: /\.js(\?.*)?$/i,
})],
},

Related

How do I compile multiple SCSS files in Webpack?

I have separate SCSS files I want to compile into separate CSS files. Here is a part of my Webpack config file:
module.exports = {
entry: ['./src/js/main.js', './src/scss/main.scss', './src/scss/additional.scss'],
output: {
filename: './assets/js/main.bundle.js',
},
plugins: [
new MiniCssExtractPlugin({
filename: './assets/css/main.bundle.css',
}),
],
modules: {...}
}
The example above will only compile main.scss and omit additional.scss. Here is what I tried:
module.exports = {
entry: {
main: ['./src/js/main.js', './src/scss/main.scss'],
additional: './src/scss/additional.scss',
},
output: {
filename: './assets/js/[name].bundle.js',
},
plugins: [
new MiniCssExtractPlugin({
filename: './assets/css/[name].bundle.css',
}),
],
modules: {...}
}
This kinda works, however this will also generate an additional.bundle.js which I don't need (I only need one JavaScript output and two CSS files). Any ideas?
Here is the solution I can up with. You basically need to create separate config objects for scss and everything else:
module.exports = [{
entry: {
main: ['./src/js/main.js'],
},
output: {
filename: './assets/js/[name].bundle.js',
},
modules: {...}
}, {
entry: {
main: ['./src/scss/main.scss'],
additional: ['./src/scss/additional.scss'],
},
output: {
filename: './.leftover/[name].bundle.js',
},
plugins: [
new MiniCssExtractPlugin({
filename: './assets/css/[name].bundle.css',
}),
],
modules: {...}
}]
then remove the .leftover directory on npm run build.
package.json:
"build": "webpack --mode production && del-cli dist/.leftover"
Not the cleanest solution, however that's the only one I can think of.

how can I exclude some folders containing .vue files from being built in vuejs?

module.exports = {
presets: [
'#vue/app'
],
module:{
rules: [
{
test: /\.vue$/,
exclude: [
'./src/components/Homepages/number1',
'./src/components/Homepages/number2'
]
}
]
}
}
I am trying to include just one of 'Homepages/number1', 'Homepages/number2', 'Homepages/number3' folders in my project conditionally and others shoud be excluded from the project when running npm run build to decrease my dist folder size. I am trying this code but I am sure its not the right solution. I am doing this config in babel.config.js.
One option is to use the Copy plugin:
module.exports = {
plugins: [
new CopyPlugin({
patterns: [
{
from: path.posix.join(
path.resolve(__dirname, "src").replace(/\\/g, "/"),
"**/*"
),
globOptions: {
ignore: [
// Ignore all `txt` files
"**/*.txt",
// Ignore all files in all subdirectories
"**/subdir/**",
],
},
},
],
}),
],
};

HtmlWebpackPlugin ignores filename

I'm trying out code/bundle splitting with webpack, however I ran in to an issue. HTMLWebpackPlugin is as far as I know supposed to dynamically insert script tags into an HTML file. This HTML file is by default index.html and it seems to work when I use the default. Because I use .NET with a _Layout.cshtml and Index.cshtml, it would like it to use the Index.cshtml.
HTMLWebpackPlugin seems to completely ignore what is in "filename", and generates an index.html:
new HtmlWebpackPlugin({
template: '../../Views/Shared/_Layout.cshtml',
filename: 'test-index.html' // Generates index.html, not test-index.html...
//filename: '../Views/Home/Index.cshtml' // Not working either. Generates index.html
})
webpack.common.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var helpers = require('./helpers');
module.exports = {
entry: {
'polyfills': './ClientApp/polyfills.ts',
'vendor': './ClientApp/vendor.ts',
'app': './ClientApp/main.ts'
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loaders: [
{
loader: 'awesome-typescript-loader',
options: { configFileName: helpers.root('ClientApp', 'tsconfig.json') }
} , 'angular2-template-loader'
]
},
{
test: /\.html$/,
use: ['raw-loader']
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[hash].[ext]'
},
{
test: /\.css$/,
include: helpers.root('ClientApp', 'app'),
use: ['to-string-loader', 'css-loader']
}
]
},
optimization:
{
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
// npm package names are URL-safe, but some servers don't like # symbols
return `npm.${packageName.replace('#', '')}`;
},
},
}
}
},
plugins: [
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(#angular|fesm5)/,
helpers.root('ClientApp'),
{}
),
new webpack.BannerPlugin('© COPYRIGHT LIGHTHOUSE INTELLIGENCE ' + new Date().getFullYear()),
new HtmlWebpackPlugin({
template: '../../Views/Shared/_Layout.cshtml',
filename: 'test-index.html' // Generates index.html, not test-index.html...
//filename: '../Views/Home/Index.cshtml' // Not working either
})
]
};
webpack.dev.js:
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
mode: "development",
output: {
path: helpers.root('/wwwroot/dist'),
publicPath: '/wwwroot/dist/',
filename: '[name].js', //.[hash]
chunkFilename: '[id].js' //.chunk
},
plugins: [
new ExtractTextPlugin('[name].css'),
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
});
I dont think you cant do that. Razor cshtml file need to have everything include in the view before you build and run your project so that it can build and transform cshtml to html.
htmlwebpackplugin only work with html so the only option you can choose is serve the html file in your .net core project
Location of the output file is determined by the output attribute of webpack.config.js (path: helpers.root('/wwwroot/dist')). So you have to specify only the file name for the filename attribute.

Is there a way to expose module globally from Webpack DllPlugin vendor bundle?

Using Webpack 4, I'm creating a bundle and a vendors bundle. Vendor bundle contains jQuery and the code bundle references jquery using 'import * from jquery'. This works perfectly.
However, I now need to use a 3rd party (already minified) javascript file. That file expects jquery to be exposed as '$' on the global window object. My bundle needs to be loaded after the new minified file, also.
So I have:
<script src='./libs/jquery-3.2.1.min.js'></script>
<script src='../vendor.js'></script>
<script src="./libs/newMinifiedFile.js"></script>
<script src="../bundle.js"></script>
as my current workaround. The static jquery file links the $ objects to the global namespace, and then the vendor.js file allows me to keep using 'import' in my bundle.
So, how do I only load jquery once, and use it in both ways? This seems to be a slightly different problem than most I've seen online because of how I'm loading things.
Here's a small example of my configs right now:
const config = (isDebug) => {
const isDevBuild = isDebug;
const extractCSS = new MiniCssExtractPlugin({filename: 'vendor.css'});
const sharedConfig = {
mode: isDevBuild ? 'development' : 'production',
stats: { modules: false },
resolve: {
extensions: [ '.js' ]
},
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' },
]
},
entry: {
vendor: [
'jquery'
],
},
output: {
publicPath: 'dist/',
filename: '[name].js',
library: '[name]_[hash]',
},
plugins: [
new webpack.NormalModuleReplacementPlugin(/\/iconv-loader$/, require.resolve('node-noop')) // Workaround for https://github.com/andris9/encoding/issues/16
]
};
const clientBundleConfig = merge(sharedConfig, {
output: {
path: path.join(__dirname, 'wwwroot', 'dist'),
pathinfo: false
},
module: {
rules: [
{
test: /\.css(\?|$)/, include: path.resolve(__dirname, "client"), exclude: [/webviewer/, /redux/, /helpers/],
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
minimize: isDevBuild,
sourceMap: isDevBuild
}
}
]
}
]
},
plugins: [
extractCSS,
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
],
optimization: {
minimize: !isDevBuild,
removeAvailableModules: false,
removeEmptyChunks: false,
splitChunks: false,
},
});
And in my normal config I use:
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require(path.join(__dirname, 'wwwroot', 'dist', 'vendor-manifest.json'))
})
So, I can find jquery in the global 'vendor_hash' object, but I can't get it to map it to $ no matter what I try (Most plugins seem to see that $ is never used in any of the code I'm supplying for the bundle and thus don't seem to include it). If I add something like this in my 'entry.js' file then it still doesn't work:
window.$ = window.jQuery = require("jquery");

push assets folder to public directory with webpack

I'm using Webpack for the first time. Currently everything is being served up quite nicely. My problem is when I'm trying to build a dist folder. Currently I get my index.html and bundle.js files but I can't figure out how to push my assets to the dist folder.
I have file-loader loaded up but it doesn't actually seem to do what I want it to and none of the google searches I've run are telling me what I need to know. Below is my config file. Can someone lead a horse to water? Also once I get it running do I need to import all of images to my React components?
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.scss$/, use: [ 'style-loader', 'css-loader', 'sass-loader' ]},
{ test: /\.(png|jpe?g|svg|)$/, use: { loader: 'file-loader', options: }}
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
Looks like I just needed to use Copy-Webpack-Plugin.
To copy all the assets from 'app/assets/' to 'dist/assets/' I just needed to do:
plugins: [
new CopyWebpackPlugin([
{ from: 'app/assets', to: 'assets' }
])
]
First install copy webpack plugin:
npm i copy-webpack-plugin
Then in the webpack.config.json:
const CopyPlugin = require("copy-webpack-plugin");
module.exports = {
plugins: [
new CopyPlugin({
patterns: [
{ from: "src/public", to: "" } //to the dist root directory
],
}),
],
};

Categories

Resources