How to use webpack

Comprehensive webpack code examples:

How to use webpack.dev:

11
12
13
14
15
16
17
18
19
20
### 文件目录
```sh
└── static # 项目静态文件目录
    ├── build
    │   ├── webpack.base.config.js # 基础编译脚本
    │   ├── webpack.dev.config.js # 开发环境编译脚本
    │   └── webpack.prod.config.js # 生产环境编译脚本
    ├── output # 编译后输出目录
    │   ├── asset
    │   ├── dist

How to use webpack.ids:

190
191
192
193
194
195
196
197
198
199
new HtmlWebpackPlugin({
  chunksSortMode: 'none',
  template: plib.join(__dirname, 'templates', 'template.html'),
  title: jlab.name || 'JupyterLab'
}),
new webpack.ids.HashedModuleIdsPlugin(),
// custom plugin for ignoring files during a `--watch` build
new WPPlugin.FilterWatchIgnorePlugin(ignored),
// custom plugin that copies the assets to the static directory
new WPPlugin.FrontEndPlugin(buildDir, jlab.staticDir),

How to use webpack.NoErrorsPlugin:

40
41
42
43
44
45
46
47
48
config.devtools = '#inline-source-map';

if (environment === 'development') {
  config.plugins.push(
    new Webpack.HotModuleReplacementPlugin(),
    new Webpack.NoErrorsPlugin(),
    new WebpackError(process.platform)
  );
}

How to use webpack.TerserPlugin:

147
148
149
150
151
152
153
154
155
156
],
optimization: {
  nodeEnv: false,
  // minimize: false,
  minimizer: [
    new TerserPlugin({
      // parallel: true,
      terserOptions: { mangle: false, output: { beautify: true, indent_level: 2 } }, // comments: false
      extractComments: false,
    }),

How to use webpack.ReplaceCodePlugin:

139
140
141
142
143
144
145
146
147
148
  new BannerPlugin({
    banner: '#!/usr/bin/env node\nrequire("v8-compile-cache");',
    raw: true,
    test: /\bcli\.js$/,
  }),
  new ReplaceCodePlugin([
    { search: /( require\("\.\/)vendor\//g, replace: '$1', test: /\bvendor[\\/][\w-]*\.js$/ }, //
  ]),
],
optimization: {

How to use webpack.CopyPlugin:

123
124
125
126
127
128
129
130
131
132
    (o, x) => ((o[`${x}$`] = `${__dirname}/node_modules/${x}/src/index.ts`), o),
    { 'css-what$': __dirname + '/node_modules/css-what/src/parse.ts' }
  ),
},
plugins: [
  new CopyPlugin({
    patterns: [
      { from: 'node_modules/svgo/LICENSE*', to: '../[name][ext]' },
      {
        from: 'node_modules/svgo/lib/*.ts',

How to use webpack.base:

66
67
68
69
70
71
72
73
74
75

module.exports = babelConfig;

```

#### webpack.base.config.js
```js
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

How to use webpack.WebpackError:

173
174
175
176
177
178
179
180
181
182
                        failOnError: false,
                        onDetected: function ({ module: _webpackModuleRecord, paths, compilation }) {
                                if (paths.some(p => p.includes('container.ts'))) return;

                                // @ts-ignore
                                compilation.warnings.push(new WebpackError(paths.join(' -> ')));
                        },
                }),
        );
}

How to use webpack.DllReferencePlugin:

48
49
50
51
52
53
54
55
56
57
plugins: [
  // It is possible to require the ckeditor5-dll.manifest.json used in
  // core/node_modules rather than having to install CKEditor 5 here.
  // However, that requires knowing the location of that file relative to
  // where your module code is located.
  new webpack.DllReferencePlugin({
    manifest: require('./node_modules/ckeditor5/build/ckeditor5-dll.manifest.json'), // eslint-disable-line global-require, import/no-unresolved
    scope: 'ckeditor5/src',
    name: 'CKEditor5.dll',
  }),

How to use webpack.prod:

120
121
122
123
124
125
126
127
128
129
  test: /\.svg$/i,
  issuer: /\.[jt]sx?$/,
  use: [{ loader: '@svgr/webpack', options: { icon: true } }]
},
// {
//   test: /\.(svg)(\?.*)?$/, // for reducing file-size: OptimizeCSSAssetsPlugin > cssnano > SVGO, that congigured in webpack.prod.js
//   exclude: /(fonts\\.+\.svg)(\?.*)?/,
//   type: "asset",
//   generator: {
//     filename: "images/[name][ext][query]", // [hash][ext][query]",

How to use webpack.WatchIgnorePlugin:

97
98
99
100
101
102
103
104
105
106
const visualJSFilePath = visualPackage.buildPath(tsconfig.compilerOptions.out || tsconfig.compilerOptions.outDir);
this.webpackConfig.output.path = path.join(visualPackage.basePath, config.build.dropFolder);
this.webpackConfig.output.filename = "[name]";
let visualPluginPath = path.join(process.cwd(), config.build.precompileFolder, visualPlugin);
this.webpackConfig.plugins.push(
    new webpack.WatchIgnorePlugin({ paths: [visualPluginPath] })
);
if (tsconfig.compilerOptions.out) {
    this.webpackConfig.entry = {
        "visual.js": visualJSFilePath

How to use webpack.EvalSourceMapDevToolPlugin:

110
111
112
113
114
115
116
117
118
119
  __COMMIT_HASH__: JSON.stringify(commitHash || "DEV"),
}),
// In dev mode, use a faster method of create sourcemaps
// while keeping lines/columns accurate
isDevServer &&
  new webpack.EvalSourceMapDevToolPlugin({
    // Exclude vendor files from sourcemaps
    // This is a huge speed improvement for not much loss
    exclude: ["vendor"],
    columns: true,

How to use webpack.NamedChunksPlugin:

96
97
98
99
100
101
102
103
104
105
new ScriptExtHtmlWebpackPlugin({
  // `runtime` must same as runtimeChunk name. default is `runtime`
  inline: /runtime\..*\.js$/,
}),
// keep chunk.id stable when chunk has no name
new webpack.NamedChunksPlugin((chunk) => {
  if (chunk.name) {
    return chunk.name;
  }
  const modules = Array.from(chunk.modulesIterable);

How to use webpack.config:

395
396
397
398
399
400
401
402
403
404
  # publish = "build"
  # functions build directory
  functions = "functions-build" # always appends `-build` folder to your `functions` folder for builds
```

### webpack.config.netlify.js

**Do not forget to add this Webpack config, or else problems may occur**

```js

How to use webpack.HashedModuleIdsPlugin:

216
217
218
219
220
221
new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery",
    "window.jQuery": "jquery"
}),
new webpack.HashedModuleIdsPlugin(),

How to use webpack.DllPlugin:

8
9
10
11
12
13
14
15
16
17
  path: path.join(__dirname, '../static/js'),
  filename: '[name].dll.js',
  library: '[name]_library'
},
plugins: [
  new webpack.DllPlugin({
    path: path.join(__dirname, '.', '[name]-manifest.json'),
    name: '[name]_library'
  }),
  new webpack.optimize.UglifyJsPlugin({

How to use webpack.container:

24
25
26
27
28
29
30
31
32
33
output: {
  filename: 'feature-app.federated.js',
  publicPath: '/',
},
plugins: [
  new webpack.container.ModuleFederationPlugin({
    name: '__feature_hub_feature_app_module_container__',
    exposes: {
      featureAppModule: path.join(__dirname, './feature-app'),
    },

How to use webpack.SourceMapDevToolPlugin:

194
195
196
197
198
199
200
201
202
203
    })
);

if (options.devtool === "source-map" && this.webpackConfig.devServer.port) {
    this.webpackConfig.plugins.push(
        new webpack.SourceMapDevToolPlugin({
            filename: '[file].map',
            publicPath: `https://localhost:${this.webpackConfig.devServer.port}/assets/`
        })
    );

How to use webpack.ContextReplacementPlugin:

92
93
94
95
96
97
98
99
100
101
new MiniCssExtractPlugin({
  filename: `../css/[name].bundle${BUNDLE_PREFIX}.css`,
  chunkFilename: `../css/[name].chunk${BUNDLE_PREFIX}.css`,
  ignoreOrder: false, // Enable if there are warnings about conflicting order
}),
new webpack.ContextReplacementPlugin(
  /react-intl\/locale-data/,
  localesRegExp,
),
new webpack.ContextReplacementPlugin(

How to use webpack.ProgressPlugin:

17
18
19
20
21
22
23
24
25
26
devServer: {
  static: distDir,
  port: 9000
},
plugins: [
  new webpack.ProgressPlugin(),
  new WebpackModules(),
  new CleanWebpackPlugin({ protectWebpackAssets: false }),
  new CopyPlugin([{ from: 'public', to: '.' }]),
  new CompressionPlugin()

How to use webpack.NormalModuleReplacementPlugin:

41
42
43
44
45
46
47
48
49
50
 *
 * Thanks goes to Yarn's lead maintainer @arcanis for helping me get to this
 * solution.
 */
plugins.push(
  new NormalModuleReplacementPlugin(/^@babel\/runtime(.*)/, (resource) => {
    const path = resource.request.split('@babel/runtime')[1];

    resource.request = require.resolve(`@babel/runtime${path}`);
  })

How to use webpack.ModuleFederationPlugin:

46
47
48
49
50
51
52
53
54
55
      }
    }
  ]
},
plugins: [
  new ModuleFederationPlugin({
    name: 'Aegis',
    filename: 'remoteEntry.js',
    library: {
      name: 'Aegis',

How to use webpack.EnvironmentPlugin:

216
217
218
219
220
221
222
223
224
},

plugins: [
  // Ignore any of our optional modules if they aren't installed. This ignores database drivers
  // that we aren't using for example.
  new EnvironmentPlugin({ WEBPACK: true }),
  new IgnorePlugin({
    checkResource: resource => {
      const baseResource = resource.split('/', resource[0] === '@' ? 2 : 1).join('/');

How to use webpack.BannerPlugin:

77
78
79
80
81
82
83
84
85
86
87
	})
);


// Adds a banner to the top of each generated chunk.
webpackConfig.plugins.push(
    new webpack.BannerPlugin(`
	Boot Helpers

	@source: https://github.com/xizon/boot-helpers
	@version: ${json.version} (${moment().format( "MMMM D, YYYY" )})

How to use webpack.IgnorePlugin:

69
70
71
72
73
74
75
76
77
78
},
plugins: [
  // new CleanWebpackPlugin([outputDir], { verbose: false }),
  // This saves us a bunch of bytes by pruning locales (which we don't use)
  // from moment.
  new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  new webpack.NoEmitOnErrorsPlugin(),
],
resolve: {
  extensions: ['.js', '.ts', '.tsx'],

How to use webpack.NamedModulesPlugin:

160
161
162
163
164
165
166
167
168
169
    return 'script';
  },
  include: 'allChunks'
  //include: ['app']
}),
new webpack.NamedModulesPlugin(),
new WorkboxPlugin.GenerateSW({
  clientsClaim: true,
  skipWaiting: true,
  importWorkboxFrom: 'local',

How to use webpack.NoEmitOnErrorsPlugin:

20
21
22
23
24
25
26
27
28
29
new webpack.DefinePlugin({
  NODE_ENV: config.dev.env.NODE_ENV
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
  filename: 'index.html',
  template: 'index.html',

How to use webpack.HotModuleReplacementPlugin:

19
20
21
22
23
24
25
26
27
28
plugins: [
  new webpack.DefinePlugin({
    NODE_ENV: config.dev.env.NODE_ENV
  }),
  // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
  new webpack.HotModuleReplacementPlugin(),
  new webpack.NoEmitOnErrorsPlugin(),
  // https://github.com/ampedandwired/html-webpack-plugin
  new HtmlWebpackPlugin({
    filename: 'index.html',

How to use webpack.LoaderOptionsPlugin:

83
84
85
86
87
88
89
90
91
92
plugins: [
  new webpack.DefinePlugin({
    BROWSER_RUNTIME: !!process.env.BROWSER_RUNTIME,
  }),
  new NodePolyfillPlugin(),
  new webpack.LoaderOptionsPlugin({
    debug: true,
  }),
  new HtmlWebpackPlugin({
    title: "seath",