How can I stop HTML being output to the compiled app.js? - javascript

I am using Webpack 2 for my portfolio website, but it's not an SPA - therefore, the intention is not to output everything into my bundled JS.
I have a few entry points for the .pug, .scss and .js files. Like so:
entry: {
app: [
path.resolve(__dirname, 'src/pug/app.pug'),
path.resolve(__dirname, 'src/js/app.js'),
path.resolve(__dirname, 'src/scss/app.scss')
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].js'
}
However, when looking at the source for the app.js, I see the rendered HTML from my .pug files.
For the .pug compiling, I'm using HtmlWebpackPlugin. I guess the easiest way for me to explain what's going on is to show you the webpack.config.babel.js file:
import webpack from 'webpack';
import path from 'path';
import autoprefixer from 'autoprefixer';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import SvgStorePlugin from 'external-svg-sprite-loader/lib/SvgStorePlugin';
import bourbon from 'bourbon';
import neat from 'bourbon-neat';
const extractScss = new ExtractTextPlugin({
filename: 'css/[name].css',
allChunks: true
});
const config = {
entry: {
app: [
path.resolve(__dirname, 'src/pug/app.pug'),
path.resolve(__dirname, 'src/js/app.js'),
path.resolve(__dirname, 'src/scss/app.scss')
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].js'
},
module: {
rules: [
{
test: /\.pug$/,
use: [
{
loader: 'html-loader'
},
{
loader: 'pug-html-loader',
options: {
pretty: false,
exports: false
}
}
]
},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
['es2015']
]
}
}
]
},
{
test: /\.(jpe?g|png|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '/images/[name].[ext]'
}
},
{
loader: 'image-webpack-loader',
options: {
progressive: false,
optipng: {
optimizationLevel: 7,
quality: '90',
speed: 5
},
mozjpeg: {
quality: 90
},
gifsicle: {
interlaced: false
}
}
}
]
},
{
test: /\.svg$/,
use: [
{
loader: 'external-svg-sprite-loader',
query: {
name: 'svg/sprite.svg',
iconName: '[name]'
}
}
]
},
{
test: /\.scss$/,
use: extractScss.extract([
{
loader: 'css-loader'
},
{
loader: 'postcss-loader',
options: {
plugins() {
return [
autoprefixer({
browsers: ['last 2 versions', 'Explorer >= 9', 'Android >= 4']
})
];
}
}
},
{
loader: 'sass-loader',
options: {
includePaths: [
bourbon.includePaths,
neat.includePaths
]
}
}
])
}
]
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
stats: 'errors-only',
open: false
},
plugins: [
new SvgStorePlugin(),
new HtmlWebpackPlugin({
title: 'Portfolio',
minify: {
collapseWhitespace: true
},
hash: true,
template: 'src/pug/app.pug',
filetype: 'pug',
filename: 'index.html'
}),
extractScss
]
}
process.traceDeprecation = false;
export default config;
I don't see any CSS in the app.js bundle and the entry point is setup just the same, so might it have something to do with the HtmlWebpackPlugin itself? Perhaps I'm not understanding how this works correctly and my configuration is wrong.
I'm new to Webpack (coming from Gulp), so please bear with me if the answers to my questions seem rather obvious.
Thanks for your help.
Update:
For reference, my project structure is as follows:
And I would call an image from my .pug file in /pug/components/example.pug with a path like img(src="../images/example.jpg"). This worked prior to removing .pug as an entry point in the Webpack config as user Tatsuyuki suggested below.

Do not add the template as an source:
app: [
// path.resolve(__dirname, 'src/pug/app.pug'),
path.resolve(__dirname, 'src/js/app.js'),
path.resolve(__dirname, 'src/scss/app.scss')
]
Instead, specify the template option for HtmlWebpackPlugin:
new HtmlWebpackPlugin({
template: 'src/index.pug'
})
Reference

Related

Webpack not making JS modules

I want to make vanilla js/bootstrap website and I am using webpack. I have been following various instructions and tutorials but they do not seem to work.
Here is my webpack.config.js:
const path = require('path')
module.exports = {
entry: {
auth: [
path.resolve(__dirname, 'src/js/auth.js'),
path.resolve(__dirname, 'src/js/msal-2.28.1.js')
]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
entry: {
main: [
path.resolve(__dirname, 'src/js/index.js'),
path.resolve(__dirname, 'src/js/api.js')
]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
static: path.resolve(__dirname, 'dist'),
port: 3000,
hot: true
},
module: {
rules: [
{
test: /\.(scss)$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: () => [
require('autoprefixer')
]
}
}
},
{
loader: 'sass-loader'
}
]
}
]
}
}
But the error I get when I run webpack is:
Module not found: Error: Can't resolve 'auth' in '/Users/me/Projects/AProject/src/js'
Did you mean './auth'?
All of the .js files exist where they should:
Image of JS files in correct folder structure
So I am at a loss as to what is going on. If I remove the second entry point (main) it builds fine no errors.
I have treid following every single tutorial and guide I can find and it just doesn't work.
Thanks to #Juho Vepsäläinen
There were two errors occuring:
I had an import for auth.js in api.js
I have multiple entry: points and apparently JS will only use the last one.
Here is working config:
const path = require('path')
module.exports = {
entry: {
auth: [
path.resolve(__dirname, 'src/js/auth.js'),
path.resolve(__dirname, 'src/js/msal-2.28.1.js')
],
main: [
path.resolve(__dirname, 'src/js/index.js'),
path.resolve(__dirname, 'src/js/api.js')
]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
static: path.resolve(__dirname, 'dist'),
port: 3000,
hot: true
},
module: {
rules: [
{
test: /\.(scss)$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: () => [
require('autoprefixer')
]
}
}
},
{
loader: 'sass-loader'
}
]
}
]
}
}

Webpack shows white screen

After I've added webpack in my react app, once the webpack started, it shows the white screen, and the whole bundle gets downloaded at one time. Even though I've done code splitting in react.
my webpack config:
/* eslint-disable no-un`enter code here`def */
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlWebpackInjectPreload = require("#principalstudio/html-webpack-inject-preload");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: path.resolve(__dirname, './index.js'),
devtool: "inline-source-map",
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js",
publicPath: '/'
},
devServer: {
contentBase: path.resolve(__dirname, 'build'),
port: 4000,
hot: true,
},
resolve: {
extensions: [".*",".js", ".jsx", ".css"],
fallback: {
stream: false
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: ["babel-loader"],
},
{
test: /\.css$/,
exclude: /\.module\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.module\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: { importLoaders: 2, modules: true },
},
"postcss-loader",
],
},
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
use: [
{
loader: "url-loader",
options: {
limit: 8192,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve('./index.html')
}),
new CleanWebpackPlugin(),
new HtmlWebpackInjectPreload({
files: [
{
match: /.*\.woff2$/,
attributes: { as: "font", type: "font/woff2", crossorigin: true },
},
{
match: /\.[a-z-0-9]*.css$/,
attributes: { as: "style" },
},
],
}),
],
};
The attached bundle image also gets larger up to 19MB. What's going wrong I'm not able to figure out.

How to ignore error js script tag from html on running webpack with HtmlWebpackPlugin?

How can i ignore the script tag in Html webpack plugin?
Because I have added this
<script src="cordova.js"/>
tag into my index.html template anonymously for my app development.
See my configuration in Webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "www"),
filename: "./js/build/[name].build.js",
chunkFilename: "./js/build/[name].build.js",
// publicPath: "./js/build/",
},
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: "./",
},
},
"css-loader?url=false",
"sass-loader",
],
},
{
test: /\.html$/,
use: ["html-loader"],
},
{
test: /\.(svg|png|jpeg|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "res",
},
},
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: "./css/build/[name].css",
// chunkFilename: "../css/[id].css"
}),
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
// new BundleAnalyzerPlugin()
],
// devtool: "inline-source-map",
};
I just wanted to ignore the script on production and I have researched this many times but unfortunately I don't see any solution
So, if I got the problem right, you want to ignore a certain resource when bundling for production.
The html-loader has an option to filter sources based on attribute, attribute value, context file and anything you have available in you webpack.config.js.
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Assuming you are passing arguments to your webpack config like argv.mode
const PRODUCTION = true;
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "www"),
filename: "./js/build/[name].build.js",
chunkFilename: "./js/build/[name].build.js",
// publicPath: "./js/build/",
},
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: "./",
},
},
"css-loader?url=false",
"sass-loader",
],
},
{
test: /\.html$/,
use: {
loader: "html-loader",
options: {
sources: {
urlFilter: (attribute, value, resourcePath) => {
if (PRODUCTION && /cordova.js$/.test(value)) {
return false;
}
return true;
},
}
},
},
},
{
test: /\.(svg|png|jpeg|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "res",
},
},
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: "./css/build/[name].css",
// chunkFilename: "../css/[id].css"
}),
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
// new BundleAnalyzerPlugin()
],
// devtool: "inline-source-map",
};
In the html module rule, I added an options property to html-loader with an example how you could ignore a certain resource with urlFilter. Check the html-loader docs on filtering resources
You will need to get a reference to the variables you passed to your cli like --mode eg. line 5-6. (Not in the current example) See webpack docs on env vars.

Webpack 4 - Add css file to multiple html files

I want to bundle a couple of html files and add one css files into all of them. But my webpack configuration add only css and js bundled files to index.html
My files looks like this:
I want to add this main-hash.js and main-hash.css to all HTML files: about.html, index.html, contact.html
Also when I exclude index.html (comment below) from file-loader my index.html don't recognize paths for public folder /images. Any ideas ??
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/main.js',
output: {
filename: '[name]-[hash:8].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.ProgressPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
}),
new MiniCssExtractPlugin({
filename: '[name].[hash:8].css'
}),
new CleanWebpackPlugin()
],
module: {
rules: [
{
test: /.(js|jsx)$/,
include: [path.resolve(__dirname, 'src')],
loader: 'babel-loader',
options: {
plugins: ['syntax-dynamic-import'],
presets: [
[
'#babel/preset-env',
{
modules: false
}
]
]
},
exclude: '/node_modules/'
},
{
test: /\.(png|jpeg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
publicPath: './src/images',
outputPath: './assets',
name: '[name].[ext]'
}
}
]
},
{
test: /\.(html)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].html'
}
},
{ loader: 'extract-loader' },
{
loader: 'html-loader',
options: {
attrs: ['img:src']
}
}
],
// HERE
exclude: path.resolve(__dirname, './src/index.html')
},
{
test: /\.sass$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
'css-loader',
'sass-loader'
]
}
]
},
optimization: {
splitChunks: {
cacheGroups: {
vendors: {
priority: -10,
test: /[\\/]node_modules[\\/]/
}
},
chunks: 'async',
minChunks: 1,
minSize: 30000,
name: true
}
},
devServer: {
open: true
}
};
You can add multiple instances of the HtmlWebpackPlugin, one for each of your html files:
plugins: [
new webpack.ProgressPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
}),
new HtmlWebpackPlugin({
filename: 'about.html',
template: './src/about.html'
}),
new HtmlWebpackPlugin({
filename: 'contact.html',
template: './src/contact.html'
}),
new MiniCssExtractPlugin({
filename: '[name].[hash:8].css'
}),
new CleanWebpackPlugin()
],
This should inject the JS and CSS files into each html file.

Adding a csv file to a webpack build

I have placed a csv file in my assets folder for my react app, however, that file is not getting picked up and added to my dist build via webpack (the images are still added as assets to the build but the csv file is not). You can see my webpack build below. So how do I add a csv file to my dist build via webpack (the goal is for users of my app to be able to download this file)? Thanks!
webpack.dev.js
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const config = merge(common, {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
historyApiFallback: true,
hot: true,
proxy: {
'/api': {
target: 'http://localhost:5001',
secure: false,
},
},
allowedHosts: [
'localhost',
'fatpandadev'
],
public: 'fatpandadev:8080'
},
});
module.exports = config;
webpack.common.js
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const DIST_DIR = path.resolve(__dirname, "dist");
const SRC_DIR = path.resolve(__dirname, "src");
const config = {
entry: [
"babel-polyfill",
`${SRC_DIR}/app/index.js`,
`${SRC_DIR}/app/assets/stylesheets/application.scss`,
`${SRC_DIR}/app/components/index.scss`,
"font-awesome/scss/font-awesome.scss",
"react-datepicker/dist/react-datepicker.css",
"rc-time-picker/assets/index.css",
"react-circular-progressbar/dist/styles.css",
"#trendmicro/react-toggle-switch/dist/react-toggle-switch.css",
],
output: {
path: `${DIST_DIR}/app/`,
filename: "bundle.js",
publicPath: "/app/"
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
failOnWarning: false,
failOnError: true
}
},
{
test: /\.js$/,
include: SRC_DIR,
loader: 'babel-loader',
query: {
presets: ['react', 'stage-2']
}
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: ['file-loader?context=src/images&name=images/[path][name].[ext]', {
loader: 'image-webpack-loader',
query: {
mozjpeg: {
progressive: true,
},
gifsicle: {
interlaced: false,
},
optipng: {
optimizationLevel: 7,
},
pngquant: {
quality: '75-90',
speed: 3,
},
},
}],
exclude: path.resolve(__dirname, "node_modules"),
include: __dirname,
},
{
test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
// loader: "url?limit=10000"
use: "url-loader"
},
{
test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
use: 'file-loader'
},
{
test: /\.(txt|csv)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "application.css"
})
]
};
module.exports = config;
(this answer is only referenced on the server side)
In addition to #PlayMa256,
On Server side(Nodejs runtime), you may need emitFile: true
{
test: /\.(txt|csv|mmdb)$/,
use: [
{
loader: 'file-loader',
options: {
name: "[path][name].[ext]",
emitFile: true,
},
},
],
},
Refer to this PR: https://github.com/webpack-contrib/file-loader/pull/135
In my opinion, file-loader way seem to better than copy-webpack-plugin way.
You can test like below:
import csvPath from './assets/data.csv'
console.log(csvPath) // assets/data.csv
Tested version:
$ cat node_modules/webpack/package.json | jq .version
"4.29.5"
$ cat node_modules/file-loader/package.json | jq .version
"3.0.1"
You might want to check the CopyWebpackPlugin if you have no need to process/parse the files, but only to copy them to your dist folder.
Copy Webpack Plugin
Copies individual files or entire directories to the build directory
Install
npm i -D copy-webpack-plugin
Usage
webpack.config.js
const CopyWebpackPlugin = require('copy-webpack-plugin')
const config = {
plugins: [
new CopyWebpackPlugin([ ...patterns ], options)
]
}
Patterns
A simple pattern looks like this
{ from: 'source', to: 'dest' }
{
test: /\.(txt|csv)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
You should import you csv file as you import your images too.
import your csv files using raw-loader,
{
test: /\.csv$/i,
use: 'raw-loader',
}

Categories

Resources