Webpack configuration is always forgotten, record the base configuration in nuggets

1. Download dependencies first

npm init -y / / initialization
npm i webpack webpack-cli -D // These are the most basic dependencies of WebPack
Copy the code

Add the script script build: webpack to package.json

2. Create a webpack. Config. Js

The file should follow CommonJS to expose an object

The configurations are as follows:

  • Entry: An entry file that indicates which module WebPack should use
  • Output: packages the output configuration
  • Module (loader) : Configure to handle other files (non-JS and JSON files)
  • Plugin: Loaders are used to transform certain types of modules, while plug-ins can be used to perform a wider range of tasks. Including: package optimization, resource management, injection of environment variables.
  • mode: Sets the production environmentproductionAnd the development environmentdevelopment

Base directory environment (TS is used in the example) :

This example demonstrates the use of auto-packaged TS files and HTML injection so you need to download three dependencies:

npm i html-webpack-plugin typescript ts-loader -D
Copy the code
├ ─ node_modules ├ ─ SRC │ ├ ─ app. Ts │ ├ ─ but ts │ └ ─ index. The HTML ├ ─ package. The json ├ ─ tsconfig. Json └ ─ webpack. Config. JsCopy the code
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry:'./src/index.ts'.// Import file
    output: {// output
    module: {//loader
        rules: [{test: /\.ts$/,
                use:'ts-loader'.exclude:/node_modules/}},plugins: [//plugins
        new HtmlWebpackPlugin({
Copy the code

3. Pack simply

Once the above content is configured, it can be packaged automatically by running NPM run build on the terminal

Dangerous! Because this example uses TS, there is a problem with modularity

TS files imported using modularity cannot be suffixed

However, not using the suffix introduces js files by default, resulting in compilation errors

The WebPack configuration needs to be added at this point

module.exports = {
    resolve: {extensions: ['.ts'.'.js'] // Parse the suffixes in order},... }Copy the code

Then run NPM run build to pack.