Favicon implementation with react js - javascript

I have been trying to get the favicon to work with a react js app, but it looks like the process is complicated. I do have a favicon.png inside of src/images. Please see image:
And it is declared in my index.html as:
<link rel="shortcut icon" type="image/png" href="${require('./src/images/favicon.png')}"/>
I have also tried adding the following to my config.json file as:
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
favicon: './src/images/favicon-16x16.png'
})
None of the above works, and I am wondering if I am missing something?
My Webpack Config Code:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const RobotsPlugin = require('#tanepiper/robots-webpack-plugin');
// The extract text plugin moves all the required *.css modules in entry chunks into a
// separate CSS file. So your styles are no longer inlined into the JS bundle, but in a
// separate CSS file. (https://webpack.js.org/plugins/extract-text-webpack-plugin/#usage)
const extractSass = new ExtractTextPlugin({
filename: '[name].[contenthash].css',
disable: process.env.NODE_ENV === 'development',
});
module.exports = {
entry: {
// Babel Polyfill will emulate a full ES2015+ environment and is intended to be used in an
// application rather than a library/tool.
index: ['babel-polyfill', './src/index.js'],
},
target: 'web',
output: {
filename: '[name].[chunkhash].js',
path: path.resolve(__dirname, 'dist'),
},
// Loaders. Webpack uses a regular expression to determine which files it should look for
// and serve to a specific loader.
module: {
rules: [
{
test: /\.(html)$/,
include: path.join(__dirname, 'public'),
use: {
loader: 'html-loader',
options: {
interpolate: true,
},
},
},
{
test: /\.js$/,
exclude: [/node_modules/],
loader: 'babel-loader',
},
{
test: /\.js$/,
include: path.join(__dirname, 'psp247'),
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
},
],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.scss$/,
use: extractSass.extract({
use: [
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
},
],
// use style-loader in development
fallback: 'style-loader',
}),
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader'],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader',
],
},
],
},
plugins: [
new RobotsPlugin({
userAgents: [{
name: '*',
disallow: ['/'],
}]
}),
new Dotenv(),
// Generates an HTML5 file based on the template provided, includes all your webpack bundles in
// the body using script tags and styles on the head using a link tag.
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
}),
extractSass,
/* // It's also good practice to extract third-party libraries to a separate vendor chunk.
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
}),
// Extract webpack's boilerplate and manifest which can change with every build.
new webpack.optimize.CommonsChunkPlugin({
name: 'runtime',
}),
// The CommonsChunkPlugin should remove duplicate dependencies and put those into a common chunk.
new webpack.optimize.CommonsChunkPlugin({
name: 'common', // Specify the common bundle's name.
}), */
],
};

Change your favicon extension to .ico
And Change your link tag to this:
<link rel="icon" href="./src/images/favicon.ico" type="image/x-icon" />

Webpack is not needed here at all as your html file is static, and not generated using any code ( this is what i infer from the image you shared).
You also don't need require or any code to generate the href, just write the correct static url of the favicon.
Notice that however you have incorrect type, it should be like
<link rel="icon" href="Your-url-here" type="image/x-icon" />

Related

Webpack multiple entries under certain urls

Hey I have this project which has this structure:
bundler -> webpack.common.js
src -> main.js, index.html, styles.css
package.json
node_modules... the rest doesnt matter really
It is set up like when I do: npm run dev webpack creates a live server using my current main.js for my index.html
The webpack.common.js looks like this:
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCSSExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
module.exports = {
entry: path.resolve(__dirname, "../src/current_script.js"),
output: {
hashFunction: "xxhash64",
filename: "bundle.[contenthash].js",
path: path.resolve(__dirname, "../dist"),
},
devtool: "source-map",
plugins: [
new CopyWebpackPlugin({
patterns: [{ from: path.resolve(__dirname, "../static") }],
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "../src/index.html"),
minify: true,
}),
new MiniCSSExtractPlugin(),
],
module: {
rules: [
// HTML
{
test: /\.(html)$/,
use: ["html-loader"],
},
// JS
{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
// CSS
{
test: /\.css$/,
use: [MiniCSSExtractPlugin.loader, "css-loader"],
},
// Images
{
test: /\.(jpg|png|gif|svg)$/,
type: "asset/resource",
generator: {
filename: "assets/images/[hash][ext]",
},
},
// Fonts
{
test: /\.(ttf|eot|woff|woff2)$/,
type: "asset/resource",
generator: {
filename: "assets/fonts/[hash][ext]",
},
},
],
},
};
```
Now my question is how can I define multiple entries under certain URLs.
So for example now under localhost/ it will redirect me to index.html using my main.js
Is there a way of having localhost/2 use my index.html with another js file like main2.js

ReactJS - What makes bundle.js size big

I have recently completed a project on ReactJS, the only problem with the project is its production bundle.js size its around 30MB, that's insanely huge. I have used BundleAnalyzerPlugin plugin to analyse it, it looks like this
The bigger the block, bigger is the size.
node_modules=10 MB
each visible small chunks are almost = 1MB
My webpack config looks like this
webpack.base.config.js
var webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
noParse:[
'./~/xlsx/jszip.js',
],
externals:[
{'./jszip': 'jszip'}
],
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{
test: /\.json$/,
loader: "json-loader"
},
{
test: /\.(html)$/,
loader: "html-loader",
options:{
attrs:[':data-src!./src/components/preview/preview_html',':data-src!./src/components/landing/loader/index.html']
}
},
{
test: /\.(ttf|gif|eot|svg|woff|woff2|png)(\?.+)?$/,
loader: 'file-loader?name=[hash:12].[ext]'
},
{
test: /\.css?$/,
loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
},
{
test: /\.scss?$/,
loader: 'style-loader!css-loader!sass-loader'
}]
},
resolve: {
root: __dirname,
alias:{
//Have set of aliases
},
extensions: ['','.json', '.js', '.jsx','.ejs']
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new BundleAnalyzerPlugin()
],
devServer: {
historyApiFallback: true,
contentBase: './',
watchContentBase: true,
},
devtool:'cheap-module-eval-source-map'
};
webpack.prod.config.js
const merge = require('webpack-merge');
const baseConfig = require('./webpack.base.config.js');
var webpack = require('webpack');
var CompressionPlugin = require('compression-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = merge(baseConfig,{
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new HtmlWebpackPlugin({
template:'index.ejs',
hash: false,
baseHref: 'xxxx',
scripts: [
{
src: 'bundle.js',
type: 'text/javascript'
}
]
})
]
});
I have imported few css directly from node_modules into index.ejs file which looks like this
<link rel="stylesheet" href="/node_modules/react-bootstrap-switch/dist/css/bootstrap3/react-bootstrap-switch.css">
<link rel="stylesheet" href="/node_modules/draft-js/dist/Draft.css">
<link rel="stylesheet" href="/node_modules/react-select-plus/dist/react-select-plus.css">
<link rel="stylesheet" href="/node_modules/react-day-picker/lib/style.css">
<link rel="stylesheet" href="/node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css">
<script src="node_modules/xlsx/dist/shim.min.js"></script>
<script src="node_modules/xlsx/dist/xlsx.full.min.js"></script>
Need help to reduce the size, and find mistakes in config or implementation..
Thanks.
I assume you are using webpack 4. I noticed that you haven't set mode: 'production' in your production webpack config. That option will do optimisations including using terser to minify the bundle output. Also, set NODE_ENV to production, some libraries relies on the value of that variable directly.
I suggest starting with that, and also read this: https://webpack.js.org/guides/production/
After that is done, you can start identifying which 3rd party modules that are taking the most size in your vendor bundle. Then, you can consider code-splitting them so that they will be in their own separate chunks, and you can load them only when needed. You can read about code-splitting here: https://webpack.js.org/guides/code-splitting/

How to include Bootstrap into Vue Js webpack template? [duplicate]

Greetings one and all,
I have been playing around with Bootstrap for Webpack, but I'm at the point of tearing my hair out. I have literally gone through loads of blog articles and they either use the 7 months outdated 'bootstrap-webpack' plugin (which, surprisingly does not work out of the box) or.. They include the Bootstrap files through import 'node_modules/*/bootstrap/css/bootstrap.css'.
Surely, there must be a cleaner and more efficient way of going about this?
This is my current webpack.config.js file:
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var autoprefixer = require('autoprefixer');
var path = require('path');
module.exports = {
entry: {
app: path.resolve(__dirname, 'src/js/main.js')
},
module: {
loaders: [{
test: /\.js[x]?$/,
loaders: ['babel-loader?presets[]=es2015&presets[]=react'],
exclude: /(node_modules|bower_components)/
}, {
test: /\.css$/,
loaders: ['style', 'css']
}, {
test: /\.scss$/,
loaders: ['style', 'css', 'postcss', 'sass']
}, {
test: /\.sass$/,
loader: 'style!css!sass?sourceMap'
},{
test: /\.less$/,
loaders: ['style', 'css', 'less']
}, {
test: /\.woff$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff&name=[path][name].[ext]"
}, {
test: /\.woff2$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff2&name=[path][name].[ext]"
}, {
test: /\.(eot|ttf|svg|gif|png)$/,
loader: "file-loader"
}]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '/js/bundle.js',
sourceMapFilename: '/js/bundle.map',
publicPath: '/'
},
plugins: [
new ExtractTextPlugin('style.css')
],
postcss: [
autoprefixer({
browsers: ['last 2 versions']
})
],
resolve: {
extensions: ['', '.js', '.sass'],
modulesDirectories: ['src', 'node_modules']
},
devServer: {
inline: true,
contentBase: './dist'
}
};
I could go and require('bootstrap') (with some way of getting jQuery in it to work), but.. I'm curious to what you all think and do.
Thanks in advance :)
I am not sure if this is the best way, but following work for me well with vue.js webapp. You can see the working code here.
I have included files required by bootstrap in index.html like this:
<head>
<meta charset="utf-8">
<title>Hey</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="/static/bootstrap.css" type="text/css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js" integrity="sha384-XTs3FgkjiBgo8qjEjBk0tGmf3wPrWtA6coPfQDfFEY8AnYJwjalXCiosYRBIBZX8" crossorigin="anonymous"></script>
<script href="/static/bootstrap.js"></script>
</head>
And this works, you can execute the repo. Why I went this way was I had to customise some config in bootstrap so I had to change the variables file and build the code of bootstrap which outputted me bootstrap.js and bootstrap.cssfiles, which I am using here.
There is an alternative way suggested here by using the npm package and a webpack customisation.
First install bootstrap in your project:
npm install bootstrap#4.0.0-alpha.5
And make sure you can use sass-loader in your components:
npm install sass-loader node-sass --save-dev
now go to your webpack config file and add a sassLoader object with the following:
sassLoader: {
includePaths: [
path.resolve(projectRoot, 'node_modules/bootstrap/scss/'),
],
},
projectRoot should just point to where you can navigate to node_packages from, in my case this is: path.resolve(__dirname, '../')
Now you can use bootstrap directly in your .vue files and webpack will compile it for you when you add the following:
<style lang="scss">
#import "bootstrap";
</style>
I highly recommend using bootstrap-loader. You add a config file (.bootstraprc in your root folder) where you can exclude the bootstrap elements you don't want and tell where your variables.scss and bootstrap.overrides.scss are. Define you SCSS variables, do your overrides, add your webpack entry and get on with your life.
I use webpack to build bootstrap directly from .less and .scss files. This allows customizing bootstrap by overriding the source in .less/.scss and still get all the benefits of webpack.
Your code is missing an entry point for any .css/.less/.scss files. You need to include an entry point for the compiled css files. For this entry point, I declare an array with const and then include paths inside the array to the source files I want webpack to compile.
Currently, I'm using bootstrap 3 with a base custom template and also a 2nd custom theme. The base template uses bootstrap .less file styling and it has specific source overrides written in .less files.
The 2nd custom theme uses .sass file styling and has similar overrides to bootstrap's base written in .scss files. So, I need to try to optimize all this styling for production (currently coming in about 400kb but that's a little heavy because we choose to avoid CDN's due to targeting use in China).
Below is a reference webpack.config.js which works to build from .less/.scss/.css files, and also does a few other things like build typescript modules and uses Babel for converting es6/typescript to browser compatible javascript. The output ultimately ends up in my /static/dist folder.
const path = require('path');
const webpack = require('webpack');
// plugins
const ForkTsCheckerNotifierWebpackPlugin = require('fork-ts-checker-notifier-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// take debug mode from the environment
const debug = (process.env.NODE_ENV !== 'production');
// Development asset host (webpack dev server)
const publicHost = debug ? 'http://localhost:9001' : '';
const rootAssetPath = path.join(__dirname, 'src');
const manifestOptions = {
publicPath: `${publicHost}/static/dist/`,
};
const babelLoader = {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
'#babel/preset-env'
]
}
};
const app_css = [
// specific order generally matters
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'css', 'fonts', 'Roboto', 'css', 'fonts.css'),
path.join(__dirname, 'node_modules', 'font-awesome', 'css', 'font-awesome.css'),
// This is bootstrap 3.3.7 base styling writtin in .less
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'bootstrap.less'),
// bootstrap theme in .scss -> src\bp\folder\theme\src\scss\styles.scss
path.join(__dirname, 'src', 'bp', 'folder', 'theme', 'src', 'scss', 'styles.scss'),
// back to .less -> 'src/bootstrap-template1/assets/less/_main_full/core.less',
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'core.less'),
// 'src/bootstrap-template1/assets/less/_main_full/components.less',
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'components.less'),
//'src/bootstrap-template1/assets/less/_main_full/colors.less',
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'colors.less'),
// <!-- syntax highlighting in .css --> src/bp/folder/static/css/pygments.css
path.join(__dirname, 'src', 'bp', 'folder', 'static', 'css', 'pygments.css'),
// <!-- lato/ptsans font we want to serve locally --> src/fonts/googlefonts.css'
path.join(__dirname, 'src', 'fonts', 'googlefonts.css'),
// a .css style -> 'src/bp/appbase/styles/md_table_generator.css'
path.join(__dirname, 'src', 'bp', 'appbase', 'styles', 'md_table_generator.css'),
// another .css style -> hopscotch 'src/libs/hopscotch/dist/css/hopscotch.min.css'
path.join(__dirname, 'src', 'libs', 'hopscotch', 'dist', 'css', 'hopscotch.min.css'),
//LAST final custom snippet styles to ensure they take priority 'src/css/style.css',
path.join(__dirname, 'src', 'css', 'style.css')
];
const vendor_js = [
//'core-js',
'whatwg-fetch',
];
const app_js = [
// a typescript file! :)
path.join(__dirname, 'src', 'typescript', 'libs', 'md-table', 'src', 'extension.ts'),
// base bootstrap 3.3.7 javascript
path.join(__dirname, 'node_modules', 'bootstrap', 'dist', 'js', 'bootstrap.js'),
path.join(__dirname, 'src', 'main', 'app.js'),
// src/bootstrap-template1/assets/js/plugins/forms/styling/uniform.min.js'
path.join(__dirname, 'node_modules', '#imanov', 'jquery.uniform', 'src', 'js', 'jquery.uniform.js'),
// src/bootstrap-template1/assets/js/plugins/ui/moment/moment.min.js'
];
function recursiveIssuer(m) {
if (m.issuer) {
return recursiveIssuer(m.issuer);
} else if (m.name) {
return m.name;
} else {
return false;
}
}
module.exports = {
context: process.cwd(), // to automatically find tsconfig.json
// context: __dirname,
entry: {
app_css,
vendor_js,
app_js,
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: `${publicHost}/static/dist/`,
chunkFilename: '[id].[hash:7].js',
filename: '[name].[hash:7].js'
},
resolve: {
extensions: [".webpack.js", ".web.js",".tsx", ".ts", ".js", ".css"],
alias: {
jquery$: path.resolve(__dirname, 'node_modules', 'jquery', 'dist', 'jquery.js'),
}
},
target: "web",
devtool: 'source-map',
devServer: {
// this devserver proxies all requests to my python development server except
// webpack compiled files in the `/static/dist` folder
clientLogLevel: 'warning',
contentBase: path.join(__dirname, './src'),
publicPath: 'dist',
open: true,
historyApiFallback: true,
stats: 'errors-only',
headers: {'Access-Control-Allow-Origin': '*'},
watchContentBase: true,
port: 9001,
proxy: {
'!(/dist/**/**.*)': {
target: 'http://127.0.0.1:8000',
},
},
},
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCssAssetsPlugin({})],
splitChunks: {
cacheGroups: {
appStyles: {
name: 'app',
// https://webpack.js.org/plugins/mini-css-extract-plugin/#extracting-css-based-on-entry
test: (m, c, entry = 'app') =>
m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
chunks: 'all',
enforce: true,
},
},
},
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery'
}),
// Strip all locales from moment.js except "zh-cn"
// ("en" is built into Moment and can’t be removed)
new MomentLocalesPlugin({
localesToKeep: ['zh-cn'],
}),
new ForkTsCheckerWebpackPlugin({
tslint: true, useTypescriptIncrementalApi: true
}),
new ForkTsCheckerNotifierWebpackPlugin({ title: 'TypeScript', excludeWarnings: false }),
new MiniCssExtractPlugin({
filename: '[name].[hash:7].css',
chunkFilename: '[id].[hash:7].css',
moduleFilename: ({ name }) => `${name.replace('/js/', '/css/')}.[hash:7].css`
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.optimize\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', { discardComments: { removeAll: true } }],
},
canPrint: true
}),
new ManifestPlugin({
...manifestOptions
}),
].concat(debug ? [] : [
// production webpack plugins go here
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
}
}),
new ForkTsCheckerWebpackPlugin({
async: false,
useTypescriptIncrementalApi: true,
memoryLimit: 2048
}),
]),
module: {
rules: [
{
// jinja/nunjucks templates
test: /\.jinja2$/,
loader: 'jinja-loader',
query: {
root:'../templates'
}
},
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
babelLoader,
{
loader: 'ts-loader',
options:
{ // disable type checker - we will use it in
// fork-ts-checker-webpack-plugin
transpileOnly: true
}
}
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
babelLoader
]
},
{
test: /\.(html|jinja2)$/,
loader: 'raw-loader'
},
{
test: /\.(sc|sa|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
// only use if hmr is not working correctly
// reloadAll: true,
},
},
{
loader: "css-loader",
},
{
loader: "sass-loader"
},
]
},
{
test: /\.less$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
// only use if hmr is not working correctly
// reloadAll: true,
},
},
{
loader: 'css-loader', // translates CSS into CommonJS
},
{
loader: 'less-loader', // compiles Less to CSS
},
],
},
{
test: /\.(ttf|eot|svg|gif|ico)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[hash:7].[ext]',
context: rootAssetPath
},
},
],
},
{
test: /\.(jpe?g|png)$/i,
loader: 'responsive-loader',
options: {
name: '[path][name].[hash:7].[ext]',
adapter: require('responsive-loader/sharp'),
context: rootAssetPath
}
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader:'url-loader',
options:{
limit: 10000,
mimetype: 'application/font-woff',
// name: ('fonts/[path][name].[hash:7].[ext]'),
name: ('fonts/[name].[hash:7].[ext]'),
}
},
{
test: require.resolve("jquery"),
use:[
{ loader: "expose-loader", options:"$" },
{ loader: "expose-loader", options:"jQuery" },
{ loader: "expose-loader", options:"jquery" }
]
}
]
},
};

Preferred way of using Bootstrap in Webpack

Greetings one and all,
I have been playing around with Bootstrap for Webpack, but I'm at the point of tearing my hair out. I have literally gone through loads of blog articles and they either use the 7 months outdated 'bootstrap-webpack' plugin (which, surprisingly does not work out of the box) or.. They include the Bootstrap files through import 'node_modules/*/bootstrap/css/bootstrap.css'.
Surely, there must be a cleaner and more efficient way of going about this?
This is my current webpack.config.js file:
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var autoprefixer = require('autoprefixer');
var path = require('path');
module.exports = {
entry: {
app: path.resolve(__dirname, 'src/js/main.js')
},
module: {
loaders: [{
test: /\.js[x]?$/,
loaders: ['babel-loader?presets[]=es2015&presets[]=react'],
exclude: /(node_modules|bower_components)/
}, {
test: /\.css$/,
loaders: ['style', 'css']
}, {
test: /\.scss$/,
loaders: ['style', 'css', 'postcss', 'sass']
}, {
test: /\.sass$/,
loader: 'style!css!sass?sourceMap'
},{
test: /\.less$/,
loaders: ['style', 'css', 'less']
}, {
test: /\.woff$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff&name=[path][name].[ext]"
}, {
test: /\.woff2$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff2&name=[path][name].[ext]"
}, {
test: /\.(eot|ttf|svg|gif|png)$/,
loader: "file-loader"
}]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '/js/bundle.js',
sourceMapFilename: '/js/bundle.map',
publicPath: '/'
},
plugins: [
new ExtractTextPlugin('style.css')
],
postcss: [
autoprefixer({
browsers: ['last 2 versions']
})
],
resolve: {
extensions: ['', '.js', '.sass'],
modulesDirectories: ['src', 'node_modules']
},
devServer: {
inline: true,
contentBase: './dist'
}
};
I could go and require('bootstrap') (with some way of getting jQuery in it to work), but.. I'm curious to what you all think and do.
Thanks in advance :)
I am not sure if this is the best way, but following work for me well with vue.js webapp. You can see the working code here.
I have included files required by bootstrap in index.html like this:
<head>
<meta charset="utf-8">
<title>Hey</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="/static/bootstrap.css" type="text/css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js" integrity="sha384-XTs3FgkjiBgo8qjEjBk0tGmf3wPrWtA6coPfQDfFEY8AnYJwjalXCiosYRBIBZX8" crossorigin="anonymous"></script>
<script href="/static/bootstrap.js"></script>
</head>
And this works, you can execute the repo. Why I went this way was I had to customise some config in bootstrap so I had to change the variables file and build the code of bootstrap which outputted me bootstrap.js and bootstrap.cssfiles, which I am using here.
There is an alternative way suggested here by using the npm package and a webpack customisation.
First install bootstrap in your project:
npm install bootstrap#4.0.0-alpha.5
And make sure you can use sass-loader in your components:
npm install sass-loader node-sass --save-dev
now go to your webpack config file and add a sassLoader object with the following:
sassLoader: {
includePaths: [
path.resolve(projectRoot, 'node_modules/bootstrap/scss/'),
],
},
projectRoot should just point to where you can navigate to node_packages from, in my case this is: path.resolve(__dirname, '../')
Now you can use bootstrap directly in your .vue files and webpack will compile it for you when you add the following:
<style lang="scss">
#import "bootstrap";
</style>
I highly recommend using bootstrap-loader. You add a config file (.bootstraprc in your root folder) where you can exclude the bootstrap elements you don't want and tell where your variables.scss and bootstrap.overrides.scss are. Define you SCSS variables, do your overrides, add your webpack entry and get on with your life.
I use webpack to build bootstrap directly from .less and .scss files. This allows customizing bootstrap by overriding the source in .less/.scss and still get all the benefits of webpack.
Your code is missing an entry point for any .css/.less/.scss files. You need to include an entry point for the compiled css files. For this entry point, I declare an array with const and then include paths inside the array to the source files I want webpack to compile.
Currently, I'm using bootstrap 3 with a base custom template and also a 2nd custom theme. The base template uses bootstrap .less file styling and it has specific source overrides written in .less files.
The 2nd custom theme uses .sass file styling and has similar overrides to bootstrap's base written in .scss files. So, I need to try to optimize all this styling for production (currently coming in about 400kb but that's a little heavy because we choose to avoid CDN's due to targeting use in China).
Below is a reference webpack.config.js which works to build from .less/.scss/.css files, and also does a few other things like build typescript modules and uses Babel for converting es6/typescript to browser compatible javascript. The output ultimately ends up in my /static/dist folder.
const path = require('path');
const webpack = require('webpack');
// plugins
const ForkTsCheckerNotifierWebpackPlugin = require('fork-ts-checker-notifier-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// take debug mode from the environment
const debug = (process.env.NODE_ENV !== 'production');
// Development asset host (webpack dev server)
const publicHost = debug ? 'http://localhost:9001' : '';
const rootAssetPath = path.join(__dirname, 'src');
const manifestOptions = {
publicPath: `${publicHost}/static/dist/`,
};
const babelLoader = {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
'#babel/preset-env'
]
}
};
const app_css = [
// specific order generally matters
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'css', 'fonts', 'Roboto', 'css', 'fonts.css'),
path.join(__dirname, 'node_modules', 'font-awesome', 'css', 'font-awesome.css'),
// This is bootstrap 3.3.7 base styling writtin in .less
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'bootstrap.less'),
// bootstrap theme in .scss -> src\bp\folder\theme\src\scss\styles.scss
path.join(__dirname, 'src', 'bp', 'folder', 'theme', 'src', 'scss', 'styles.scss'),
// back to .less -> 'src/bootstrap-template1/assets/less/_main_full/core.less',
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'core.less'),
// 'src/bootstrap-template1/assets/less/_main_full/components.less',
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'components.less'),
//'src/bootstrap-template1/assets/less/_main_full/colors.less',
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'colors.less'),
// <!-- syntax highlighting in .css --> src/bp/folder/static/css/pygments.css
path.join(__dirname, 'src', 'bp', 'folder', 'static', 'css', 'pygments.css'),
// <!-- lato/ptsans font we want to serve locally --> src/fonts/googlefonts.css'
path.join(__dirname, 'src', 'fonts', 'googlefonts.css'),
// a .css style -> 'src/bp/appbase/styles/md_table_generator.css'
path.join(__dirname, 'src', 'bp', 'appbase', 'styles', 'md_table_generator.css'),
// another .css style -> hopscotch 'src/libs/hopscotch/dist/css/hopscotch.min.css'
path.join(__dirname, 'src', 'libs', 'hopscotch', 'dist', 'css', 'hopscotch.min.css'),
//LAST final custom snippet styles to ensure they take priority 'src/css/style.css',
path.join(__dirname, 'src', 'css', 'style.css')
];
const vendor_js = [
//'core-js',
'whatwg-fetch',
];
const app_js = [
// a typescript file! :)
path.join(__dirname, 'src', 'typescript', 'libs', 'md-table', 'src', 'extension.ts'),
// base bootstrap 3.3.7 javascript
path.join(__dirname, 'node_modules', 'bootstrap', 'dist', 'js', 'bootstrap.js'),
path.join(__dirname, 'src', 'main', 'app.js'),
// src/bootstrap-template1/assets/js/plugins/forms/styling/uniform.min.js'
path.join(__dirname, 'node_modules', '#imanov', 'jquery.uniform', 'src', 'js', 'jquery.uniform.js'),
// src/bootstrap-template1/assets/js/plugins/ui/moment/moment.min.js'
];
function recursiveIssuer(m) {
if (m.issuer) {
return recursiveIssuer(m.issuer);
} else if (m.name) {
return m.name;
} else {
return false;
}
}
module.exports = {
context: process.cwd(), // to automatically find tsconfig.json
// context: __dirname,
entry: {
app_css,
vendor_js,
app_js,
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: `${publicHost}/static/dist/`,
chunkFilename: '[id].[hash:7].js',
filename: '[name].[hash:7].js'
},
resolve: {
extensions: [".webpack.js", ".web.js",".tsx", ".ts", ".js", ".css"],
alias: {
jquery$: path.resolve(__dirname, 'node_modules', 'jquery', 'dist', 'jquery.js'),
}
},
target: "web",
devtool: 'source-map',
devServer: {
// this devserver proxies all requests to my python development server except
// webpack compiled files in the `/static/dist` folder
clientLogLevel: 'warning',
contentBase: path.join(__dirname, './src'),
publicPath: 'dist',
open: true,
historyApiFallback: true,
stats: 'errors-only',
headers: {'Access-Control-Allow-Origin': '*'},
watchContentBase: true,
port: 9001,
proxy: {
'!(/dist/**/**.*)': {
target: 'http://127.0.0.1:8000',
},
},
},
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCssAssetsPlugin({})],
splitChunks: {
cacheGroups: {
appStyles: {
name: 'app',
// https://webpack.js.org/plugins/mini-css-extract-plugin/#extracting-css-based-on-entry
test: (m, c, entry = 'app') =>
m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
chunks: 'all',
enforce: true,
},
},
},
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery'
}),
// Strip all locales from moment.js except "zh-cn"
// ("en" is built into Moment and can’t be removed)
new MomentLocalesPlugin({
localesToKeep: ['zh-cn'],
}),
new ForkTsCheckerWebpackPlugin({
tslint: true, useTypescriptIncrementalApi: true
}),
new ForkTsCheckerNotifierWebpackPlugin({ title: 'TypeScript', excludeWarnings: false }),
new MiniCssExtractPlugin({
filename: '[name].[hash:7].css',
chunkFilename: '[id].[hash:7].css',
moduleFilename: ({ name }) => `${name.replace('/js/', '/css/')}.[hash:7].css`
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.optimize\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', { discardComments: { removeAll: true } }],
},
canPrint: true
}),
new ManifestPlugin({
...manifestOptions
}),
].concat(debug ? [] : [
// production webpack plugins go here
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
}
}),
new ForkTsCheckerWebpackPlugin({
async: false,
useTypescriptIncrementalApi: true,
memoryLimit: 2048
}),
]),
module: {
rules: [
{
// jinja/nunjucks templates
test: /\.jinja2$/,
loader: 'jinja-loader',
query: {
root:'../templates'
}
},
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
babelLoader,
{
loader: 'ts-loader',
options:
{ // disable type checker - we will use it in
// fork-ts-checker-webpack-plugin
transpileOnly: true
}
}
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
babelLoader
]
},
{
test: /\.(html|jinja2)$/,
loader: 'raw-loader'
},
{
test: /\.(sc|sa|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
// only use if hmr is not working correctly
// reloadAll: true,
},
},
{
loader: "css-loader",
},
{
loader: "sass-loader"
},
]
},
{
test: /\.less$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
// only use if hmr is not working correctly
// reloadAll: true,
},
},
{
loader: 'css-loader', // translates CSS into CommonJS
},
{
loader: 'less-loader', // compiles Less to CSS
},
],
},
{
test: /\.(ttf|eot|svg|gif|ico)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[hash:7].[ext]',
context: rootAssetPath
},
},
],
},
{
test: /\.(jpe?g|png)$/i,
loader: 'responsive-loader',
options: {
name: '[path][name].[hash:7].[ext]',
adapter: require('responsive-loader/sharp'),
context: rootAssetPath
}
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader:'url-loader',
options:{
limit: 10000,
mimetype: 'application/font-woff',
// name: ('fonts/[path][name].[hash:7].[ext]'),
name: ('fonts/[name].[hash:7].[ext]'),
}
},
{
test: require.resolve("jquery"),
use:[
{ loader: "expose-loader", options:"$" },
{ loader: "expose-loader", options:"jQuery" },
{ loader: "expose-loader", options:"jquery" }
]
}
]
},
};

Webpack: Loading images from html templates

I'm trying to set up an angular project using Webpack but I can't figure out how to reference images from within html templates and have them included in the build.
My project tree is as follows:
package.json
app/
- images/
- foo.png
- scripts/
- styles/
- templates/
I'm trying to use html-loader along with url-loader and file-loader but it's just not happening.
This is an example template: app/templates/foo.html
<img src="../images/foo.png" />
Problem #1: I would like to be able to reference images relative to app/. Right now, the paths need to be relative to the template file and this will get ugly very quickly (../../../images/foo.png).
Problem #2: Even if I specify the relative path, as I have done above, the project builds successfully but nothing really happens. The paths are left as-is and no images appear in dist/.
Here is my webpack config:
var path = require('path');
var webpack = require('webpack');
var ngminPlugin = require('ngmin-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var ngAnnotatePlugin = require('ng-annotate-webpack-plugin');
module.exports = function(config, env) {
var appRoot = path.join(__dirname, 'app/')
if(!env) env = 'development';
var webpackConfig = {
cache: true,
debug: true,
contentBase: appRoot,
entry: {
app: path.join(appRoot, '/scripts/app.coffee')
},
output: {
path: path.join(__dirname, 'dist/),
publicPath: '/',
libraryTarget: 'var',
filename: 'scripts/[name].[hash].js',
chunkFilename: '[name].[chunkhash].js'
},
module: {
loaders: [
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader?outputStyle=expanded&includePaths[]=./node_modules/foundation/scss/')
},
{
test: /\.coffee$/,
loader: 'coffee-loader'
},
{
loader: 'ngtemplate?relativeTo=' + (path.resolve(__dirname, './app')) + '/!html'
},
{
test: /\.png$/, loader: "url-loader?limit=100000&mimetype=image/png&name=[path][name].[hash].[ext]"
},
{
test: /\.jpg$/, loader: "file-loader?name=[path][name].[hash].[ext]"
},
{
test: /\.(woff|woff2)(\?(.*))?$/,
loader: 'url?prefix=factorynts/&limit=5000&mimetype=application/font-woff'
},
{
test: /\.ttf(\?(.*))?$/,
loader: 'file?prefix=fonts/'
},
{
test: /\.eot(\?(.*))?$/,
loader: 'file?prefix=fonts/'
},
{
test: /\.svg(\?(.*))?$/,
loader: 'file?prefix=fonts/'
},
{
test: /\.json$/,
loader: 'json'
}
]
},
resolve: {
extensions: [
'',
'.js',
'.coffee',
'.scss',
'.css'
],
root: [appRoot],
},
singleRun: true,
plugins: [
new webpack.ContextReplacementPlugin(/.*$/, /a^/),
new webpack.ProvidePlugin({
'_': 'lodash'
}),
new ExtractTextPlugin("styles/[name].[chunkhash].css", {allChunks: true}),
new HtmlWebpackPlugin({
template: appRoot + '/app.html',
filename: 'app.html',
inject: 'body',
chunks: ['app']
})
],
devtool: 'eval'
}
if(env === 'production') {
webpackConfig.plugins = webpackConfig.plugins.concat(
new ngAnnotatePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({
'process-env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
);
webpackConfig.devtool = false;
webpackConfig.debug = false;
}
return webpackConfig;
}
If you are using HTML templates in Webpack 2, in addition to use the file-loader you need to change in your HTML:
<img src="../images/foo.png" />
to this
<img src=<%=require("../images/foo.png")%> />
Yes, you will have to do so for loading images from different path.
I had similar issue and I resolved this using file loader:
.
loaders: [{
// JS LOADER
test: /\.js$/,
loader: 'babel-loader?optional[]=runtime',
exclude: /node_modules/
}, {
// ASSET LOADER
test: /\.(woff|woff2|ttf|eot)$/,
loader: 'file-loader'
},
{
//IMAGE LOADER
test: /\.(jpe?g|png|gif|svg)$/i,
loader:'file-loader'
},
{
// HTML LOADER
test: /\.html$/,
loader: 'html-loader'
},
{
//SCSS LOADER
test: /\.scss$/,
loaders: ["style-loader", "css-loader", "sass-loader?indentedSyntax"]
}
]
Good Luck
For Webpack 5 you have to write this way:
module: {
rules: [
// other stuff above.....
{
test: /\.html$/,
use: [
{
loader: 'html-loader'
}
]
}
]
}
With Webpack 4, I was able to solve this problem by updating by html-loader to specify the root for my files. So given #syko's original structure; in webpack.config.js...
module: {
rules: [
// other stuff above.....
{
test: /\.html$/,
use: [
// ...The other file-loader and extract-loader go here.
{
loader: 'html-loader'
options: {
// THIS will resolve relative URLs to reference from the app/ directory
root: path.resolve(__dirname, 'app')
}
}
]
}
]
}
This tells the html-loader to interpret all absolute urls from the /app folder. So in our app/templates/foo.html, you can then use the following...
<img src="/images/foo.png" />
This then tells html-loader to see the above as path.resolve(__dirname, 'app', 'images', 'foo.png'). Then if you have extract-loader and/or file-loader, all the paths should be correct.
Managed to get this solution after hammering away at it for a while. The biggest confusion is where about in the loader stack the /images/foo.png is interpreted, in this case it starts at the html-loader plugin. Everything else after that, is more about how the image files are to be published.
Hope that helps.
You can use file-loader to extract images. Then using html-loader you can specify which tag-attribute combination should be processed by this loader via the query parameter attrs.
I could make it work with this configuration:
{
test: /\.(jpe?g|png|gif|svg|ico)$/i,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
}]
},
{
test: /\.(html)$/,
use: {
loader: 'html-loader',
options: {
attrs: ['img:src', 'link:href']
}
}
}
Or in angular something like this:
attrs: [':ng-src', ':ng-href']

Categories

Resources