Giter VIP home page Giter VIP logo

webpack-config's Introduction

Webpack 5 Configuration

This is my personal webpack v4 configuration, that I am using for small static projects. Feel free to contribute, improve or use it for your projects.

Contains some neat stuff out of the box!

  • jQuery
  • Bootstrap with Popper.js
  • FontAwesome

What does this configuration handles?

Common for development & production environment

  • it accepts two entry points; one for the app and one for the vendor
  • it compiles everything with relative paths, rather than absolute
  • it compiles sass/scss to the css file
  • it compiles es6 to the syntax that every browser can understand
  • it contains latest Boostrap, but with entirely modular setup; you may include only the parts that you need, as you probably won't use 70% of the framework
  • it has alias as ~ for importing your js files, no more mess with directory back-levels

Development environment

  • it runs webpack-dev-server with browser-sync support
  • it builds source-maps

Production environment

  • it minifies js
  • it minifies multiple image types (gif, png, jpg, jpeg, svg)
  • it copies all web fonts
  • it minifies all json files from data directory
  • it has subresource-integrity
  • it does not build source-maps, but you may specify it on line 216 if you want them

Commands?

It's pretty easy... You do not have a bunch of commands, just two of them:

  • npm run serve – to start with development
  • npm run build - to make it ready for production use

webpack-config's People

Contributors

dependabot[bot] avatar dvlden avatar liady avatar riyazurrazak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

webpack-config's Issues

File paths

Hey, @dvlden!
I have a problem with the build.

It does not correctly prescribe ways.
For example.

<script type="text/javascript" src="/scripts/app.js">
<link href="/styles/app.css" rel="stylesheet">
,url(/fonts/OpenSans-Regular.ttf)
background-image:url(/images/form_bg.png)

But it loads everything, if the paths are written so


<script type="text/javascript" src="scripts/app.js">
<link href="styles/app.css" rel="stylesheet">
,url(fonts/OpenSans-Regular.ttf) format("truetype")
background-image:url('../images/form_bg.png');

I did not make changes to the config

question about vendor.scss importing resources from vendor

Hi,

Thanks a lot for putting these out there! I'm using it a lot to sketch out regular css-js components.

So I'm curious: in src/styles/vendor.scss you're importing bootstrap and font awesome from a vendor directory:
@import 'vendor/bootstrap/main';

Where are you aliasing the vendor directory to node_modules? The only aliasing I found in webpack.config.js was resolve.modules and resolve.alias. Yet, none of this explicitly tells to redirect from vendor/ to node_modules/

So how does webpack knows to search in node_modules when vendor is referred to in CSS files.?

love it - but need some help ...

Hi Nenad

Thank you for your amazing work. Super cool. Your webpack config is super clean and relatively easy to understand for me.

I have taken your work and changed it a bit:

my package.json looks like this:

{
  "name": "webpack-config",
  "version": "1.1.0",
  "description": "This is my Webpack 4 configuration for static projects.",
  "scripts": {
    "watch": "webpack-dashboard -- webpack --progress --hide-modules --mode development",
    "dev": "webpack-dev-server --progress --hide-modules --mode development",
    "build": "webpack --progress --hide-modules --mode production"
  },
  "author": {
    "name": "Nenad Novaković",
    "email": "[email protected]",
    "url": "https://github.com/dvlden"
  },
  "license": "MIT",
  "browserslist": [
    "last 1 major version",
    "> 1%"
  ],
  "devDependencies": {
    "@babel/core": "^7.0.0-rc.1",
    "@babel/preset-env": "^7.0.0-rc.1",
    "autoprefixer": "^9.1.2",
    "babel-loader": "^8.0.0-beta.4",
    "browser-sync": "^2.24.6",
    "browser-sync-webpack-plugin": "^2.2.2",
    "clean-webpack-plugin": "^0.1.19",
    "copy-webpack-plugin": "^4.5.2",
    "css-loader": "^1.0.0",
    "cssnano": "^4.0.5",
    "file-loader": "^1.1.11",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "image-webpack-loader": "^4.3.1",
    "jsonminify": "^0.4.1",
    "mini-css-extract-plugin": "^0.4.1",
    "node-sass": "^4.9.3",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^7.1.0",
    "webpack": "^4.16.5",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.5",
    "webpack-subresource-integrity": "^1.1.0-rc.4",
    "webpackbar": "^2.6.3",
    "webpack-dashboard": "^2.0.0"
  },
  "dependencies": {
    "jquery": "^3.3.1"
  }
}

My config looks like this:

const path = require('path')
const webpack = require('webpack')
const minJSON = require('jsonminify')
const DashboardPlugin = require('webpack-dashboard/plugin');

const plugins = {
    progress: require('webpackbar'),
    clean: require('clean-webpack-plugin'),
    extractCSS: require('mini-css-extract-plugin'),
    // extractText: require('extract-text-webpack-plugin'),
    sync: require('browser-sync-webpack-plugin'),
    sri: require('webpack-subresource-integrity')
}

module.exports = (env = {}, argv) => {
    const isProduction = argv.mode === 'production'

    let config = {
        context: path.resolve('.'),

        entry: {
            // vendor: [
            //     '../main/src/main.js'
            // ],
            app: [
                '../main_app/src/style.scss',
                '../main_app/src/main.js'
            ]
        },

        output: {
            path: path.resolve('../main_dist'),
            publicPath: '/resources',
            filename: 'bundle.js',
            crossOriginLoading: 'anonymous'
        },

        module: {
            rules: [
                {
                    test: /\.((s[ac]|c)ss)$/,
                    use: [
                        plugins.extractCSS.loader,
                        {
                            loader: 'css-loader',
                            options: {
                                sourceMap: ! isProduction
                            }
                        },
                        {
                            loader: 'postcss-loader',
                            options: {
                                ident: 'postcss',
                                sourceMap: ! isProduction,
                                plugins: (() => {
                                    return isProduction ? [
                                        require('autoprefixer')(),
                                        require('cssnano')({
                                            preset: ['default', {
                                                minifySelectors: false
                                            }]
                                        })
                                    ] : []
                                })()
                            }
                        },
                        {
                            loader: 'sass-loader',
                            options: {
                                outputStyle: 'expanded',
                                sourceMap: ! isProduction
                            }
                        }
                    ]
                },
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: [
                                '@babel/preset-env'
                            ]
                        }
                    }
                },
                {
                    test: /\.(gif|png|jpe?g|svg)$/i,
                    exclude: /fonts/,
                    use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name: '[path][name].[ext]',
                                publicPath: '..' // use relative urls
                            }
                        },
                        {
                            loader: 'image-webpack-loader',
                            options: {
                                bypassOnDebug: ! isProduction,
                                mozjpeg: {
                                    progressive: true,
                                    quality: 65
                                },
                                optipng: {
                                    enabled: false
                                },
                                pngquant: {
                                    quality: '65-90',
                                    speed: 4
                                },
                                gifsicle: {
                                    interlaced: false
                                }
                            }
                        }
                    ]
                },
                {
                    test: /.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
                    exclude: /images/,
                    use: [{
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            publicPath: '../main_dist/fonts/' // use relative urls
                        }
                    }]
                }
            ]
        },

        devServer: {
            contentBase: path.join('../main_app', 'src'),
            port: 3000,
            overlay: {
                warnings: true,
                errors: true
            },
            quiet: true,
            // open: true
        },

        plugins: (() => {
            let common = [
                new plugins.extractCSS({
                    filename: '[name].css'
                }),
                new plugins.progress({
                    color: '#5C95EE'
                })
            ]

            const production = [
                new plugins.clean(['dist']),
                new plugins.sri({
                    hashFuncNames: ['sha384'],
                    enabled: true
                })
            ]

            const development = [
                new plugins.sync(
                    {
                        host: 'localhost',
                        port: 3000,
                        proxy: 'http://localhost:3000/'
                    },
                    {
                        reload: true
                    }

                ),
                //auto updating on dev server
                new webpack.HotModuleReplacementPlugin(),
                //shows relative path in HotModuleReplacement
                new webpack.NamedModulesPlugin(),
                //sexy dashboard
                new DashboardPlugin()
            ]

            return isProduction
                ? common.concat(production)
                : common.concat(development)
        })(),

        devtool: (() => {
            return isProduction
                ? '' // 'hidden-source-map'
                : 'source-map'
        })(),

        resolve: {
            modules: [
                'node_modules',
                path.resolve('../main_app/node_modules'),
                path.resolve('../node_modules'),
                path.resolve('../main/node_modules')
            ],
            alias: {
                // '~': path.resolve(__dirname, 'src/scripts/'),
                site: path.resolve(`./../../`),
                base: path.resolve(`../main/src/`),
                app: path.resolve(`../main_app/src/`),
                'jquery': 'jquery/dist/jquery',
                'jQuery': 'jquery/dist/jquery'
            }
        }
    }

    return config
};

I want to achieve two things:

  1. browser hotloading. I am not sure exactly how this works. I can see all the cool stuff at http://localhost:3001/ but I have no idea how it works. I tried to add this:
                //auto updating on dev server
                new webpack.HotModuleReplacementPlugin(),
                //shows relative path in HotModuleReplacement
                new webpack.NamedModulesPlugin(),

but that does not work. I basically want the CSS / JS to update as soon as I save the source file.

As you may have noticed I am a webpack novice!

  1. I want to set up a output of the CSS in two files: app.css and a editor.css. The latter should contain only selected styles (includes) from my src folder.

Other things to note:

  • I don't really understand what browser sync actually does, even though it looks impressive
  • I like to add the webpack dashboard, it is not a must, but it seemed to help me in the past.

It would be great if you can give me some hints.

The reason I want all this is to put it into this module: https://github.com/sunnysideup/silverstripe-sswebpack_engine_only. I am working on small projects with an environmental slant, such as https://ngaru.com

If you can help then that would be great.

Thank you

Nicolaas

Image paths after build

Hey guys,

the problem i am having is after i build all the image paths are starting with ../images/ which is fine for images used in CSS but not in HTML :(

HTML image link need to be images/ or ./images/

If i replace line 98 in config (publicPath: '..' ) then CSS is not working.

How can i change that?

ps. Hvala Nenade :)

BrowserSync

// new plugins.sync({

I've uncommented all the lines that are associated with BrowserSync

After starting dev, I see this message

[Browsersync] Watching files...
events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: ENOSPC: no space left on device, watch '/home/skiptyler/webpack-config/node_modules/is-descriptor/node_modules/kind-of'
    at FSWatcher.start (fs.js:1407:26)
    at Object.fs.watch (fs.js:1444:11)
    at createFsWatchInstance (/home/skiptyler/webpack-config/node_modules/chokidar/lib/nodefs-handler.js:37:15)
    at setFsWatchListener (/home/skiptyler/webpack-config/node_modules/chokidar/lib/nodefs-handler.js:80:15)
    at FSWatcher.NodeFsHandler._watchWithNodeFs (/home/skiptyler/webpack-config/node_modules/chokidar/lib/nodefs-handler.js:228:14)
    at FSWatcher.NodeFsHandler._handleDir (/home/skiptyler/webpack-config/node_modules/chokidar/lib/nodefs-handler.js:407:19)
    at FSWatcher.<anonymous> (/home/skiptyler/webpack-config/node_modules/chokidar/lib/nodefs-handler.js:455:19)
    at FSWatcher.<anonymous> (/home/skiptyler/webpack-config/node_modules/chokidar/lib/nodefs-handler.js:460:16)
    at FSReqWrap.oncomplete (fs.js:183:5)
Emitted 'error' event at:
    at FSWatcher._handleError (/home/skiptyler/webpack-config/node_modules/chokidar/index.js:257:10)
    at createFsWatchInstance (/home/skiptyler/webpack-config/node_modules/chokidar/lib/nodefs-handler.js:39:5)
    at setFsWatchListener (/home/skiptyler/webpack-config/node_modules/chokidar/lib/nodefs-handler.js:80:15)
    [... lines matching original stack trace ...]
    at FSReqWrap.oncomplete (fs.js:183:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] dev: `webpack-dev-server --progress --mode development`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/skiptyler/.npm/_logs/2018-06-06T15_34_26_297Z-debug.log
"browser-sync": "^2.24.4",
    "browser-sync-webpack-plugin": "^2.2.2",

How to solve this problem?
Thank you!

unneeded import

Since I don't have twitter, I felt I needed to give you some kind of feedback on, otherwise, the great advice you shared. I tweaked it for my own simpler needs, but I guess it won't hurt if you clean the webpack.config.js from the unused requre('webpack')
I'd definitely use this as a reference for the postCSS config section and maybe other stuff.
Cheers,
Kostadin

csscomb

loader: 'postcss-loader',

Hey. Is it possible to configure a postcss-loader so that it would collect all the medita requests at the end of the file?
I use scss, and prescribe media requests so

.footer {
	height: 80px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	@media screen and (max-width: 600px){
		height: 120px;
		justify-content: space-around;
		flex-direction: column-reverse;
	}
}

when I used the csscomb with a gulp.
Can I add this function here?

Fonts output problem

There are font files generated in dist folder, they're referenced in output css folder.
The fonts folder is ignored.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.