npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

webpack-config-create-utils

v1.1.2

Published

webpack config utils with default loaders and plugin, which help create webpack.config file

Downloads

3

Readme

webpack-config-create-utils

webpack config utils with default loaders and plugin, which help create webpack.config file

npm version

Install

npm i -D webpack-config-create-utils

Initialization

const {
	  	getBuildMode,
		getDefaultPlugins,
		getResolveExtensions,
		getStyleRules,
		getScriptRules,
		getFileRules,
		getAliasFromFile
	  } = require('webpack-config-create-utils')()

Methods

getBuildMode

Return data relative nodeEnv var

  • Install cross env
npm i -D cross-env
  • Add to package.json
"scripts": {
    "start": "cross-env NODE_ENV=development webpack server --mode development --open --hot",
    "build": "cross-env NODE_ENV=production webpack --mode production"
}
  • Use methods and variables
const {
		isDev,
		isProd,
		buildModeByNodeEnv,
		getFileNameByMode,
		optimizationSettingsByMode
	} = getBuildMode(})
	
module.exports = {
    //...
    
	mode: buildModeByNodeEnv,
	devtool: isDev ? 'source-map' : false,
	output: {
    		filename: getFileNameByMode('js')
    },
    optimization: optimizationSettingsByMode
    
    //...
}	
  • buildModeByNodeEnv - use development or production mode, relative nodeEnv
  • getFileNameByMode - add Hash to files for production version
  • optimizationSettingsByMode - enable Css nano and Terser for production version

getResolveExtensions(additionalExtensionsArray)

Return array with file extensions, which webpack will parse

['.js', '.jsx', '.ts', '.tsx', '.json', '.css', '.less', '.scss', '.sass', '.svg', '.png', '.jpg', '.jpeg', '.webp', '.eot', '.ttf', '.woff2', '.php'

Example
const extensions = getResolveExtensions(['.sjs', '.amd'])

module.exports = {
    //...
    
	output: {...},
    resolve: {extensions},
   
    //...
}	

getResolveExtensions(additionalExtensionsArray)

Return array with file extensions, which webpack will parse

['.js', '.jsx', '.ts', '.tsx', '.json', '.css', '.less', '.scss', '.sass', '.svg', '.png', '.jpg', '.jpeg', '.webp', '.eot', '.ttf', '.woff2', '.php'

Example
const extensions = getResolveExtensions(['.sjs', '.amd'])

module.exports = {
    //...
    
	output: {...},
    resolve: {extensions},
   
    //...
}	

getDefaultPlugins

return default plugins HtmlWebpackPlugin, CleanWebpackPlugin, MiniCssExtractPlugin

Example
const {isProd} = getBuildMode(),
      defaultPlugins = getDefaultPlugins({isProd})

module.exports = {
	//...

	entry: ['@babel/polyfill', './index.tsx'],
	plugins: [
		...defaultPlugins
	]
	
	//...
}

getStyleRules(additionalRulesConfig)

return object with style loaders

    {
        ...miniCssExtractLoader
    },
    {
        loader: 'css-loader',
        options: {
            sourceMap: true
        }
    },
    {
        loader: 'postcss-loader',
        options: {
            sourceMap: true
        }
    },
    {
        loader: 'group-css-media-queries-loader',
        options: {
            sourceMap: true
        }
    },
    {
        loader: preprocessorLoader,
        options: {
            sourceMap: true,
            webpackImporter: false
        }
    },
    {
        loader: 'grand-parent-loader'
    },
    {
        loader: 'style-resources-loader',
        options: {
            patterns: filesForImport
        }
    }
Example
const styleRules = getStyleRules(
	{
	    sassFilesForImport: ['./sass/import-mixin.sass'],
	    lessFilesForImport: [],                 
		additionalLoaders: [
			{
				loader: 'sass-parser-loader',
				pushBefore: 'sass-loader'
			}
		],
		additionalLessLoaders = [],
		additionalSassLoaders = []
	}
)


module.exports = {
    //...
    
    module: {
    		rules: [
    			...styleRules,
    		]
    }
    
    //...
}
      getScriptRules = require('./utils/rules/script-rules'),
      getFileRules = require('./utils/rules/file-rules')

getScriptRules(scriptSettingConfig)

return object with js, ts and babel loaders

{
    loader: 'babel-loader',
    options: {
        presets: ['@babel/preset-env', '@babel/preset-typescript', frameworkPresets = '@babel/preset-react', ...additionalBabelPresets],
        plugins: ['@babel/plugin-proposal-class-properties', ...additionalBabelPlugins]
    }
}
Example
const scriptRules = getScriptRules({
    additionalBabelPlugins: [],
    additionalBabelPresets: [],
    additionalLoaders: []
})

module.exports = {
    //...
    
    module: {
    		rules: [
    			...scriptRules,
    		]
    }
    
    //...
}

getFileRules

enable file loader for images, and svg like svg-code

Example
const fileRules = getFileRules()

module.exports = {
    //...
    
    module: {
    		rules: [
    			...fileRules
    		]
    }
    
    //...
}
load svg like svg code

import imgUrl, {ReactComponent as Img} from './image.svg'

export default function App() {


	return (<div>
        <img src={imgUrl} alt="img"/>
        <Img/> // return svg code
    </div>)
}

if use file loader in ts, and ts dont see imgs, add custom.d.ts to your ts file

custom.d.ts

declare module '*.svg' {
    import React = require('react');
    export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
    const src: string;
    export default src;
}

declare module '*.jpg';
declare module '*.jpeg';
declare module '*.png';
declare module '*.webp';

tsconfig.json

"compilerOptions": {
    ...
  },
  "include": [
    "custom.d.ts"
  ]

getAliasFromFile

get alias for webpack, written on tsconfig rules

Example
const alias = getAliasFromFile(__dirname) // default load tsconfig.json
const alias = getAliasFromFile(__dirname, 'alias.json') // can read file with alias, with next structure

//alias.json
{
  "paths": {
    "@src/*": ["src/*"]
  }
}

module.exports = {
    //...

	output: {},
	resolve: {
	    alias
	},
	
	//...
}

Full config example

const path = require('path'),
	  getFileRelativeConfigFile = (filePath) => path.resolve(__dirname, filePath),
	  {
	  	getBuildMode,
		getDefaultPlugins,
		getResolveExtensions,
		getStyleRules,
		getScriptRules,
		getFileRules,
		getAliasFromFile
	  } = require('webpack-config-create-utils')()

const {
		isDev,
		isProd,
		buildModeByNodeEnv,
		getFileNameByMode,
		optimizationSettingsByMode
	} = getBuildMode(),
	defaultPlugins = getDefaultPlugins({isProd}),
	extensions = getResolveExtensions(),
	alias = getAliasFromFile(__dirname),
    fileRules = getFileRules(),
	styleRules = getStyleRules(),
	scriptRules = getScriptRules()


module.exports = {
	context: getFileRelativeConfigFile('src'),
	mode: buildModeByNodeEnv,
	devtool: isDev ? 'source-map' : false,
	entry: ['@babel/polyfill', './index.tsx'],
	output: {
		filename: getFileNameByMode('js'),
		path: getFileRelativeConfigFile( 'dist')
	},
	resolve: {
	    extensions,
	    alias
	},
	optimization: optimizationSettingsByMode,
	devServer: {
		overlay: true
	},
	plugins: [
		...defaultPlugins
	],
	module: {
		rules: [
			...styleRules,
			scriptRules,
            ...fileRules
		]
	}
}

Author

webster6667