How to add header comments to webpack uglified JavaScript? - javascript

I am currently using the following webpack.config.js:
var webpack = require('webpack');
module.exports = {
entry: __dirname + "/src/index.js",
output: {
path: __dirname,
filename: "index.js"
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: '/node_modules/',
query: {
presets: ['latest']
}
}
]
},
plugins: [ new webpack.optimize.UglifyJsPlugin({minimize: true}) ]
}
This works exactly how I want it to. But now I want to add some comments with project info to the output file, on top of the one line with uglified code. How do I do this?

Add the comments to the code after minification using Webpack's BannerPlugin():
const webpack = require('webpack');
new webpack.BannerPlugin(banner);
// or
new webpack.BannerPlugin(options);

Related

Source mapping with webpack for express server

I have an express server that is written in es5 and es6 combined. It consists of js and ts files. So now when I make a webpack build and start the server, it runs fine. But if my code throws an error then the error tracing is not correct i.e source of error (file, line and column number) is not showing correctly.
Is there a way to map the bundle with the source?
I have tried adding:
devTool: "source-map" to webpack config but it doesn't work, it seems to be working with the browser. Is there any way to achieve the same for server-side as well?
Here is my webpack.config.js
const nodeExternals = require("webpack-node-externals");
const webpack = require("webpack");
const path = require("path");
module.exports = {
stats: "detailed",
target: "node",
externals: [nodeExternals()],
entry: {
app: "./server.js",
backupCronApp: "./backup/cron/index.js"
},
output: {
path: path.join(__dirname, "/build"),
filename: "[name].js",
libraryTarget: "commonjs2",
},
plugins: [new webpack.EnvironmentPlugin(["NODE_ENV"])],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
};

How to render CSS using webpack

I'm new to all this, so I apologise in advance if my question seems stupid. I'm having trouble including my CSS file using webpack. My webpack.config.js file looks like this
const HTMLWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: __dirname + '/app/index.js',
resolve: {
modules: [__dirname, 'node_modules']
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
}
]
},
output: {
filename: 'transformed.js',
path: __dirname + '/build'
},
plugins: [
HTMLWebpackPluginConfig,
new ExtractTextPlugin('styles.css')
]
};
When webpack does its thing, my CSS file is not included. I've gone through five or six different tutorials dealing with html-webpack-plugin and different loaders but I can't get it to work.
Try using both css-loader and style-loader together, instead of falling back to one. Like so:
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
CSS loader makes sure to load any necessary imports and files, while style-loader should actually inject the CSS into the webpage.
Taken from the style-loader docs: https://github.com/webpack-contrib/css-loader#usage
Are you requiring/importing the CSS file into your entry point file (or any of the files imported by the entry point)?
As in import './file.css';

Webpack file-loader not exporting images

I am using webpack for my PHP and React project. I want to load a background image from my .scss file with the webpack file-loader but for some reason I don't know, the img-folder does not get copied/exported to my dist-folder. Below is the webpack.config.js:
var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var WatchLiveReloadPlugin = require('webpack-watch-livereload-plugin');
var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");
var extractPlugin = new ExtractTextPlugin({
filename: 'main.css'
});
module.exports = {
entry: ['babel-polyfill', SRC_DIR + "/app/index.js"],
output: {
path: DIST_DIR + "/app",
filename: "bundle.js",
publicPath: "/dist"
},
watch: true,
module: {
rules: [
{
test: /\.js$/,
include: SRC_DIR,
loader: "babel-loader",
exclude: /node_modules/,
query: {
presets: ["react", "es2015", "stage-2"], plugins: ["transform-decorators-legacy", "transform-class-properties"]
}
},
{
test: /\.scss$/,
use: extractPlugin.extract({
fallback: "style-loader",
use: ["css-loader", "sass-loader", "resolve-url-loader"]
})
},
{
test: /\.css$/,
use: ["css-loader", "sass-loader", "resolve-url-loader"]
},
{
test: /\.(jpg|png)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'img/',
publicPath: 'img/'
}
}
]
}
]
},
plugins: [
extractPlugin,
new WatchLiveReloadPlugin({
port: 'localhost',
files: [
'./dist/app/*.css',
'./dist/**/*.js',
'./src/app/**/*.png',
'./src/app/**/*.jpg',
'./src/app/**/.*.scss',
'./src/**/*.php',
'./src//*.js'
]
})
]
};
I also tried loader: 'file-loader?name=/dist/img/[name].[ext]', but with no luck.
My file structure is like this:
-- dist
-- app
bundle.js
main.css
-- src
-- app
-- css
main.scss
-- img
someimage.jpg
Then in my .scss i tried this:
background-image: url('/img/someimage.jpg');
Does anyone have an idea what's wrong here?
Try to import the image file in one of your script files like
import '/path/to/img.jpg';
this will let Webpack know about the dependency and copy it.
The CSS/Sass loaders do not translate URLs that start with a /, therefore your file-loader won't be applied here.
The solution is to use relative paths for the imports if you want them to be processed by webpack. Note that CSS and Sass have no special syntax for relative imports, so the following are equivalent:
url('img/someimage.jpg')
url('./img/someimage.jpg')
If you want them to be resolved just like a module, webpack offers the possibility to start the import path with a ~, as shown in sass-loader - imports.

webpack output filename config error

When I try to run npm run webpack, this shows "Error: 'output.filename' is required, either in config file or as --output-filename."
The config file is named correctly as webpack.config.js and is also in the root directory.
Below is the content in the config file:
var path = require('path');
var webpack = require('webpack');
module.exports - {
entry: './app.js',
output: { path: __dirname, filename: 'bundle.js' },
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node-modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
};
Would really appreciate help
You have a syntax error.
module.exports -
should be:
module.exports =
And btw, you do not need to require webpack in the configuration file.

Webpack error when importing CSS vendor library into index.js

I am moving existing javascript vendor libraries into a webpack setup, where possible using npm to install an npm module and deleting the old script tag on the individual page as bundle.js and bundle.css include it
In index.js, I have the following
import 'materialize-css/dist/css/materialize.min.css';
However, when webpack is run, it errors with the following
Module parse failed: .......Unexpected character ''
You may need an appropriate loader to handle this file type.
So, for some reason, webpack is looking at the entire materialize folder, rather than just the single minified css file, and is then error when it comes across materialize/fonts directory.
I am unclear why this is happening, and what to do to stop it. Any advice would be greatly appreciated.
My webpack config is below
const webpack = require('webpack');
const path = require('path');
var precss = require('precss');
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var postcssImport = require('postcss-import');
module.exports = {
context: __dirname + '/frontend',
devtool: 'source-map',
entry: "./index.js",
output: {
filename: 'bundle.js',
path: path.join(__dirname, './static')
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', '!css-loader?sourceMap&importLoaders=1!postcss-loader')
}
]
},
plugins: [
new ExtractTextPlugin("si-styles.css")
],
postcss: function(webpack) {
return [
postcssImport({ addDependencyTo: webpack }), // Must be first item in list
precss,
autoprefixer({ browsers: ['last 2 versions'] })
];
},
}

Categories

Resources