webpack-blocks

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 常用JavaScript包
软件类型 开源软件
地区 不详
投 递 者 束敏学
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

webpack-blocks

Functional building blocks for your webpack config: easier way to configure webpack and to shareconfiguration between projects.

Ready to use blocks to configure popular tools like Babel, PostCSS, Sass, TypeScript, etc.,as well as best practices like extracting CSS — all with just one line of configuration.

Note: This is the documentation of webpack-blocks v2, compatible with webpack 4. Check out thev1 branch if you need to be compatible withwebpack 3 or older.

"Finally, webpack config done right. (...) Webpack clearly wants to stay low-level. So it makestotal sense to outsource configuring it to well designed blocks instead of copy-paste."

Dan Abramov viatwitter (Co-author of Redux, CreateReact App and React Hot Loader)

Table of contents

Installation

npm install --save-dev webpack webpack-blocks
# or
yarn add --dev webpack webpack-blocks

Example

The following sample shows how to create a webpack config with Babel support, dev server andAutoprefixer.

const webpack = require('webpack')
const {
  createConfig,
  match,

  // Feature blocks
  babel,
  css,
  devServer,
  file,
  postcss,
  uglify,

  // Shorthand setters
  addPlugins,
  setEnv,
  entryPoint,
  env,
  setOutput,
  sourceMaps
} = require('webpack-blocks')
const autoprefixer = require('autoprefixer')
const path = require('path')

module.exports = createConfig([
  entryPoint('./src/main.js'),
  setOutput('./build/bundle.js'),
  babel(),
  match(['*.css', '!*node_modules*'], [
    css(),
    postcss({
      plugins: [
        autoprefixer({ browsers: ['last 2 versions'] })
      ]
    })
  ]),
  match(['*.gif', '*.jpg', '*.jpeg', '*.png', '*.webp'], [
    file()
  ]),
  setEnv({
    NODE_ENV: process.env.NODE_ENV
  }),
  env('development', [
    devServer(),
    devServer.proxy({
      '/api': { target: 'http://localhost:3000' }
    }),
    sourceMaps()
  ]),
  env('production', [
    uglify(),
    addPlugins([new webpack.LoaderOptionsPlugin({ minimize: true })])
  ])
])

See shorthand setters and helpers documentation.

All blocks, like babel or postcss are also available as their own small packages,webpack-blocks package wraps these blocks, shorthand setters and helpers as a single dependencyfor convenience.

More examples

CSS modules:

const { createConfig, match, css } = require('webpack-blocks')

// ...

module.exports = createConfig([
  // ...
  match(['*.css', '!*node_modules*'], [
    css.modules()
  ]
])

TypeScript:

const { createConfig } = require('webpack-blocks')
const typescript = require('@webpack-blocks/typescript')

// ...

module.exports = createConfig([
  // ...
  typescript()
])

Custom blocks

Need a custom block? A simple block looks like this:

module.exports = createConfig([
  // ...
  myCssLoader(['./styles'])
])

function myCssLoader() {
  return (context, { merge }) =>
    merge({
      module: {
        rules: [
          Object.assign(
            {
              test: /\.css$/,
              use: ['style-loader', 'my-css-loader']
            },
            context.match // carries `test`, `exclude` & `include` as set by `match()`
          )
        ]
      }
    })
}

If we use myCssLoader in match() then context.match will be populated with whatever we set inmatch(). Otherwise there is still the test: /\.css$/ fallback, so our block will work withoutmatch() as well.

Check out the sample app to see a webpack config in action or readhow to create your own blocks.

Available webpack blocks

Helpers

Helpers allow you to structure your config and define settings for particular environments (likeproduction or development) or file types.

  • group
  • env
  • match
  • when

Shorthand setters

Shorthand setters gives you easier access to common webpack settings, like plugins, entry points andsource maps.

  • addPlugins
  • customConfig
  • defineConstants
  • entryPoint
  • performance
  • resolve
  • setContext
  • setDevTool
  • setEnv
  • setOutput
  • sourceMaps

Third-party blocks

Missing something? Write and publish your own webpack blocks!

Design principles

  • Extensibility first
  • Uniformity for easy composition
  • Keep everything configurable
  • But provide sane defaults

FAQ

How to debug?

In case the webpack configuration does not work as expected you can debug it usingq-i:

const { print } = require('q-i')

module.exports = createConfig([
  // ...
])

print(module.exports)
How does env() work?

env('development', [ ... ]) checks the NODE_ENV environment variable and only applies itscontained webpack blocks if it matches the given string.

So make sure you set the NODE_ENV accordingly:

// your package.json
"scripts": {
  "build": "cross-env NODE_ENV=production webpack",
  "start": "cross-env NODE_ENV=development webpack-dev-server"
}

If there is no NODE_ENV set then it will treat NODE_ENV as if it was development. Usecross-env to make it work on all platforms.

What does defineConstants() do?

defineConstants() is a small convenience wrapper around webpack'sDefinePlugin. It is composableand automatically encodes the values. Use it to replace constants in your code by their values atbuild time.

So having a defineConstants({ 'process.env.FOO': 'foo' }) and adefineConstants({ 'process.env.BAR': 'bar' }) in your config means the resulting webpack configwill contain a singlenew webpack.DefinePlugin({ 'process.env.FOO': '"FOO"', 'process.env.BAR': '"BAR"' }), thusreplacing any occurrence of process.env.FOO and process.env.BAR with the given values.

You can also use setEnv method to defineprocess.env.* variables, it’s based onwebpack.EnvironmentPlugin:setEnv({ FOO: 'foo' }).

What does a block look like from the inside?

A webpack block is a function and requires no dependencies at all ( �� �� ), thus making it easy towrite your own blocks and share them with your team or the community.

Take the babel webpack block for instance:

/**
 * @param {object} [options]
 * @param {RegExp|Function|string}  [options.exclude]   Directories to exclude.
 * @return {Function}
 */
function babel(options = { cacheDirectory: true }) {
  return (context, util) =>
    util.addLoader(
      Object.assign(
        {
          // we use a `MIME type => RegExp` abstraction here in order to have consistent regexs
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: [{ loader: 'babel-loader', options }]
        },
        context.match
      )
    )
}

Add a README and a package.json and you are ready to ship.

For more details see How to write a block.

I need some custom webpack config snippet!

No problem. If you don't want to write your own webpack block you can use customConfig():

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { addPlugins, customConfig } = require('@webpack-blocks/webpack')

// ...

module.exports = createConfig([
  // ...
  addPlugins([
    // Add a custom webpack plugin
    new HtmlWebpackPlugin({
      inject: true,
      template: './index.html'
    })
  ]),
  customConfig({
    // Add some custom webpack config snippet
    resolve: {
      extensions: ['.js', '.es6']
    }
  })
])

The object you pass to customConfig() will be merged into the webpack config usingwebpack-merge like any other webpack block's partialconfig.

How to compose blocks?

Got some projects with similar, yet not identical webpack configurations? Create a “preset”, afunction that returns a group of blocks so you can reuse it in multiple projects:

const { createConfig, env, group, babel, devServer } = require('webpack-blocks')

function myPreset(proxyConfig) {
  return group([babel(), env('development', [devServer(), devServer.proxy(proxyConfig)])])
}

module.exports = createConfig([
  myPreset({
    '/api': { target: 'http://localhost:3000' }
  })
  // add more blocks here
])

The key feature is the group() method which takes a set of blocks and returns a new block thatcombines all their functionality.

Like what you see?

Support webpack-blocks by giving feedback,contributing to this repository, publishing newwebpack blocks or just by �� starring the project!

Contributors

These awesome people have helpedwebpack-blocks by adding features, fixing bugs and refactoring code. You can become one of them!

License

MIT

  • 文章首发于个人blog,欢迎关注~ webpack hmr webpack-dev-server 在使用 webpack-dev-server 的过程中,如果指定了 hot 配置的话(使用 inline mode 的前提下), wds 会在内部更新 webpack 的相关配置,即将 HotModuleReplacementPlugin 加入到 webpack 的 plugins 当中。 HotMo

  • 一、编写可维护的webpack构建配置 栗子:构建配置包设计 构建配置抽离成npm包的意义 通过性:业务开发者无需关注构建配置;统一团队构建脚本 可维护性:构建配置合理的拆分;reademe,changelog文档 质量:冒烟测试,单元测试,测试覆盖率;持续继承   构建配置管理的可选方案 1)通过多个配置文件管理不同环境的构建,webpack --config参数进行控制使用的配置文件,如 基础

  • 官方issue:https://github.com/LLK/scratch-blocks/issues/1620 在使用scratch-blocks时,遇到build编译失败,百度查了下解决方案,发现没有一篇能解决我这个问题,查不到相关的解决方案,于是我就去github的issue寻找是否有人与我相同遇到这种情况,查看了几篇文章终于发现了能解决的方案,分享给大家,希望能帮助到遇到相同问题的后来者

  • webpack-4.0更新日志(翻译) 前言 纯手打翻译,也有小部分比较生硬的翻译,原谅那部分我也没太懂? 大改动 环境 不在支持Nodejs 4。源代码已经更新到一个较高的ecmascript版本。 使用 你必须在两种模式中选择一个(mode或者--mode): production 或者 development production 会开放所有优化功能去创建一个最优化的包 developmen

  • 前言 纯手打翻译,也有小部分比较生硬的翻译,原谅那部分我也没太懂? 大改动 环境 不在支持Nodejs 4。源代码已经更新到一个较高的ecmascript版本。 使用 你必须在两种模式中选择一个(mode或者--mode): production 或者 development production 会开放所有优化功能去创建一个最优化的包 development 开放注释和提示,并开启eval de

  • 重读webpack5 webpack5发布于2020年的国庆节之后,主要特点有:用持久性缓存来提高构建性能、用更好的算法和默认值来改进长期缓存、用更好的 Tree Shaking 和代码生成来改善包大小… 基础补充 关于harmony modules ES2015 modules 又叫做 harmony modules 关于副作用: webpack的 side effect副作用,是指在impor

  • webpack webpack配置中文https://www.webpackjs.com/concepts/ 以下为自己动手搭建开发项目(react)相关基础配置环境,非脚手架搭建环境 基础配置 => 能保证项目正常跑起来,没什么大问题 注:以下配置文件均放置在项目根目录下 1. webpack.config.js 主配置文件,未更改名默认为webpack.config.js文件,存放项目根目录

  • 如果你喜欢这系列的文章,欢迎star我的项目,源码地址,点击这里 webpack 引入 eslint 首先安装webpack支持eslint三件套: yarn add eslint eslint-loader eslint-friendly-formatter -D yarn add eslint eslint-loader eslint-friendly-formatter -D 然后修改we

 相关资料
  • 更改历史 * 2017-11-12 王莹 webpack内容更新 第一章 webpack介绍 1.1 概述 Webpack 是当下最热门的前端资源模块化管理和打包工具。它可以将许多松散的模块按照依赖和规则打包成符合生产环境部署的前端资源。还可以将按需加载的模块进行代码分隔,等到实际需要的时候再异步加载。通过 loader 的转换,任何形式的资源都可以视作模块,比如 CommonJs

  • art-template loader for webpack. Install npm install art-template npm install art-template-loader --save-dev Usage By default every local <img src="image.png"> is required (require('./image.png')).

  • Webpack 是一个模块打包器,主要目的是在浏览器上打包 JavaScript 文件。 TL;DR 捆绑 ES 模块、CommonJS 和 AMD 模块(以及绑定)。 可以创建在运行时异步加载的单个捆绑包或多个块(以减少初始加载时间)。 在编译过程中解决了依赖性,从而减小了运行时大小。 加载程序可以在编译时对文件进行预处理,例如,将 TypeScript 转换为 JavaScript、将Hand

  • 问题内容: 我开始在开发使用的服务器端渲染应用程序的环境中工作。我对每个Webpack包在开发和生产(运行时)环境中的作用感到非常困惑。 这是我的理解摘要: :是一个软件包,是一种工具,用于将Web应用程序的不同部分结合在一起,然后捆绑成一个.js文件(通常是)。然后,结果文件将在产品环境中提供以由应用程序加载,并包含运行代码的所有必需组件。功能包括缩小代码,缩小代码等。 :是一个提供 服务器 以

  • 本文向大家介绍webpack Webpack简单示例,包括了webpack Webpack简单示例的使用技巧和注意事项,需要的朋友参考一下 示例 使用Webpack的最低要求是以下命令: Web pack将获取源文件,编译到输出目标并解决源文件中的所有依赖关系。

  • 原文地址:https://cesiumjs.org/tutorials/cesium-and-webpack/ Cesium 和 Webpack Webpack是非常强大非常流行的JavaScript 模块打包工具。它可以让开发人员以一种简单直观的 require 方式去加载各种页面需要的文件,极大的方便了开源人员对代码和资源文件进行结构化设计。当编译的时候,它会跟踪代码依赖性,把所有的模型打包到