webpack解析-從0搭建

  • 初始化包 交互式創(chuàng)建
$ npm init

執(zhí)行成功后項目會有個package.json

  • 安裝依賴

//安裝webpack
npm install --save-dev webpack webpack-cli webpack-merge
//安裝js依賴
npm install --save-dev @babel/core babel-loader @babel/plugin-syntax-dynamic-import @babel/plugin-transform-runtime @babel/runtime @babel/preset-env
//安裝樣式依賴
npm install --save-dev autoprefixer css-loader node-sass sass sass-loader postcss-loader mini-css-extract-plugin
//安裝代碼檢查
npm install --save-dev stylelint stylelint-config-standard-scss stylelint-webpack-plugin
npm install --save-dev eslint eslint-config-prettier eslint-plugin-import eslint-plugin-prettier eslint-webpack-plugin @babel/eslint-parser

執(zhí)行成功后devDependencies中會顯示安裝的依賴信息。
dependencies和devDependencies的區(qū)別在于前者用于生產(chǎn)環(huán)境,后者用于開發(fā)環(huán)境。

- 本篇為webpack5配置

--file name webpack.common.js

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');

module.exports = {
  // 使用持久化緩存,提高性能
  cache: {
    type: 'filesystem',
  },
  // 入口文件
  entry: {
    yumyUI: './src/index.js',
  },
  // 出口文件
  output: {
    filename: '[name].js',
    chunkFilename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
  // 路徑別名
  resolve: {
    alias: {
      '@': path.resolve('src'),
    },
  },
  // 模塊編譯規(guī)則
  module: {
    rules: [
      {
        test: /\.scss|css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
            },
          },
          'postcss-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024, // 8kb
          },
        },
      },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'babel-loader',
          },
        ],
      },
      {
        test: /\.(woff(2)?|ttf|otf|eot)(\?v=\d+\.\d+\.\d+)?$/,
        type: 'asset/resource',
        generator: {
          filename: 'fonts/[name][ext]',
        },
      },
    ],
  },
 //  一些插件配置
  plugins: [
    new MiniCssExtractPlugin(),
    new StyleLintPlugin({
      context: 'src',
      configFile: path.resolve(__dirname, './.stylelintrc.json'),
      files: ['**/*.scss'],
      fix: false,
      cache: true,
      emitErrors: true,
      failOnError: false,
    }),
    new ESLintPlugin(),
  ],
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
};

--file name webpack.dev.js 開發(fā)環(huán)境
開啟source-map,方便閱讀打包出的代碼有無問題。

const { merge } = require('webpack-merge');
const common = require('./webpack.common');

module.exports = merge(common, {
  mode: 'development',
  devtool: 'source-map',
});

--file name webpack.prod.js 生產(chǎn)環(huán)境

const { merge } = require('webpack-merge');
const common = require('./webpack.common');

module.exports = merge(common, {
  mode: 'production',
});

  • 執(zhí)行腳本配置
    -- 在package.json中添加如下
  "scripts": {
    "start": "webpack -w --config webpack.dev.js",
    "build": "webpack --config webpack.prod.js"
  },
  • 其他文件配置
  1. .stylelintrc.json .prettierrc.json
{
  "extends": "stylelint-config-standard-scss",
  "rules": {
    "comment-empty-line-before": null,
    "function-linear-gradient-no-nonstandard-direction": null,
    "function-whitespace-after": null,
    "no-descending-specificity": null,
    "no-duplicate-selectors": null,
    "selector-no-vendor-prefix": null,
    "property-no-vendor-prefix": null,
    "value-no-vendor-prefix": null,
    "font-family-name-quotes": null,
    "selector-type-no-unknown": null,
    "scss/no-global-function-names": null,
    "no-unknown-animations": true,
    "media-feature-name-no-unknown": [true, {
      "ignoreMediaFeatureNames": [
        "prefers-reduced-motion",
        "min--moz-device-pixel-ratio"
      ]
    }],
    "number-leading-zero": "never",
    "property-no-unknown": null,
    "rule-empty-line-before": null,
    "selector-pseudo-element-colon-notation": null,
    "shorthand-property-no-redundant-values": null,
    "string-quotes": "double",
    "value-keyword-case": null,
    "at-rule-no-unknown": [true, {
      "ignoreAtRules": ["if", "else", "warn", "each", "include", "mixin", "extend", "function", "return", "use"]
    }],
    "font-family-no-missing-generic-family-keyword": null,
    "selector-class-pattern": null,
    "selector-id-pattern": null
  },
  "ignoreFiles": [
    "dist/*.css"
  ]
}
{
  "printWidth": 80,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "all"
}

  1. .eslintrc.json
{
  "parser": "@babel/eslint-parser",
  "extends": [
    "plugin:import/recommended"
  ],
  "plugins": [
    "prettier"
  ],
  "root": true,
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  },
  "globals": {
    "jQuery": true,
    "_": true,
    "Cookies": true,
    "Backbone": true,
    "Modernizr": true,
    "Popper": true,
    "Shepherd": true,
    "Sortable": true,
    "once": true,
    "CKEDITOR": true,
    "tabbable": true
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  },
  "rules": {
    "prettier/prettier": "error",
    "consistent-return": ["off"],
    "no-underscore-dangle": ["off"],
    "max-nested-callbacks": ["warn", 3],
    "import/no-unresolved": "off",
    "import/extensions": "off",
    "import/no-mutable-exports": ["off"],
    "no-plusplus": ["warn", {
      "allowForLoopAfterthoughts": true
    }],
    "no-param-reassign": ["off"],
    "no-prototype-builtins": ["off"],
    "valid-jsdoc": ["warn", {
      "prefer": {
        "returns": "return",
        "property": "prop"
      },
      "requireReturn": false
    }],
    "no-unused-vars": ["warn"],
    "operator-linebreak": ["error", "after", { "overrides": { "?": "ignore", ":": "ignore" } }],
    "import/no-extraneous-dependencies": [ "error", { "devDependencies": [ "**/webpack.*.js" ] }],
    "import/prefer-default-export": "off",
    "func-names": "off",
    "no-restricted-syntax": "off"
  }
}
  1. .babelrc.json
{
  "presets": ["@babel/preset-env"],
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容