关于webpack:webpackconfig

10次阅读

共计 5723 个字符,预计需要花费 15 分钟才能阅读完成。

webpack-config

一、config-path

1.config-output-devserver-publicPath

简述:

   /**
    * output:
    *  - publicPath: index.html 外部的援用门路
    *  - 域名 + (缺 '/' 时,浏览器会主动增加)publicPath + filename  本地拜访时(不应用 dev-server),不必加域名
    *  - 论断: 在本地拜访,写 ''或相对路径,应用 dev-server 应用'' 或以 '/' 结尾的绝对路径
    * 
    * devServer:
    *    static:
    *       - publicPath(之前在 devServer 下): 指定本地服务所在的目录(将打包的后果放在指定目录之下)
    *       倡议将 output.publicPath 与 devServer.publicPath 保持一致
    *       - directory(之前在 devServer 下,contentPath): 咱们打包之后的资源,如果依赖其它资源,就告知去哪里找
    *       - watch:true 检测资源变动,主动刷新
    */

配置:


module.exports = {
   ...
   output: {path: path.resolve(__dirname, 'dist'),
      filename: 'bundle.js',
      publicPath: '/lg', // 默认值为 ' ' 

   },
   target: 'web',
   devServer: {
      hot: true,
      static: {
         publicPath: '/lg',
         directory:path.resolve(__dirname,'public'),
         watch: true
      },
   }
}

2.devServer 罕用配置

   devServer: {
      compress: true, // 将资源压缩之后,再返回给客户端展现
      port: 5505,    // 端口
      hot: 'only',   // 当某个模块谬误被纠正时,只会更新单个模块,true 时会更新所有模块
      open:false,    // 是否主动关上浏览器
      historyApiFallback: true ,   // 当应用前端路由申请后端时,如果路由不存在,应该应用前端路由匹配
   },

二、proxy 代理服务

解决 cros 跨域申请:

// 罕用 proxy 配置
 devServer: {
      ...
      proxy: {
         // 匹配 '/api' 结尾的申请,代理到 localhost:5500
         '/api': {
            target: 'https://jsonplaceholder.typicode.com',
            changeOrigin: true,
            pathRewrite: {'^/api': '',},
         }
      }
   },

三、resolve 模块解析规定

module.exports = {
     ...
   resolve:{extensions:['.js','.jsx','.json','.ts','.vue'],
   },
}


// 引入模块时,可简写
import About from './components/About'; // About.jsx

配置门路别名:

resolve:{
      ...
    alias:{'@':path.resolve(__dirname,'src'),
      }
   },

// 应用别名简化导入模块是的书写门路
import Home from '@/components/Home';

四、dev-tools 配置

a.source-map

source-map -->  在调试的时候能够定位到源代码的信息
该模式,会生成.map 文件,用于浏览器定位源代码

配置:

   mode:'development', // development 会主动开启 devtool: 'eval' eval-source-map
                        // eval-source-map 与 inline-source-map 不同的是,它不会生成一个独自的文件,而是内联到打包后的文件中(dataUrl)
                        // cheap-source-map 与 cheap-module-source-map
   devtool:'source-map'

五、编译 TS

a.ts-loader 编译 ts

只能解决编译 ts 文件。不能解决一下 polyfill 一些较新的语法,且能够在编译阶段就发现 ts 语法错误

装置依赖:

yarn add -D ts-loader typescript

配置 loader 解决 ts 文件:

{
    test: /\.ts$/,
    use: ['ts-loader'],
 }

b. 应用 babel-loader 编译 ts

实现对 polyfill 的反对,ts 的语法错误,在编译阶段不能发现,在运行阶段能力发现

装置依赖:

yarn add core-js regenerator-runtime    // 实现 polyfill 性能的依赖
yarn add @babel/preset-typescript        // 实现 ts 文件的编译

配置:

// main.ts 中引入 polyfill 依赖
import 'core-js/stable';
import 'regenerator-runtime/runtime';

// webpack.config.js 中配置 babel-loader
{
    test: /\.ts$/,
    exclude: /node_modules/, 
    use: ['ts-loader'],
 }

// 配置 babel-loader 参数,实现 polyfill 性能
module.exports = {
    presets: [
        ['@babel/preset-env',{
            useBuiltIns: 'usage',
            corejs: 3,
        }],
        ['@babel/preset-typescript']
    ]
}

c. 综合

先应用 tsc 实现编译阶段的语法检错,再应用 babel-loader 的编译与 polyfill 性能
综合性命令实现性能:

    "ts_build":"npm run ck &&  webpack",
    "ck":"tsc --noEmit"

六、编译 vue

装置依赖:

yarn add -D vue@2.6 vue-loader@15 vue-template-compiler@2.6

配置 loader:

const VueLoaderPlugin = require('vue-loader/lib/plugin');

module.exports = {
   ...
   module: {
      rules: [
         ...
         {
            test: /\.less$/,
            use: [
               'style-loader',
               {
                  loader: 'css-loader',
                  options: {
                     importLoaders: 2,
                     esModule: false
                  }
               },
               'postcss-loader',
               'less-loader'
            ]
         },
         {
            test: /\.vue$/,
            loader: 'vue-loader'
         }
      ]
   },
   plugins: [
      ...
      new VueLoaderPlugin()]
}

七、打包环境的辨别

分写 webpack 配置文件

-config
    -webpack.common.js
    -webpack.dev.js
    -webpack.prod.js

启动命令传参:

  "scripts": {
    "build": "webpack",
    "serve": "webpack serve",
    "build2": "webpack --config ./config/webpack.common.js --env production",
    "serve2": "webpack serve --config ./config/webpack.common.js --env development"

  },

门路解决模块:

const path = require('path');
const appDir = process.cwd();
console.log(appDir,'<----- appDir');

module.exports =  (relativePath) => path.resolve(appDir, relativePath);

依据参数辨别打包环境 webpack.common.js:

// webpack.config.js

const resolvePath = require('./paths');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {merge} = require('webpack-merge');  // 合并 webpack 配置

// 定义对象保留 base 配置
const commonConfig = {
   entry: './src/main.js', // 反而没有报错(相对路径)context: resolvePath('./'),  // 以后次打包的上下文  默认是所写的配置文件的门路上下文
   output: {path: resolvePath('./dist'),
      filename: 'bundle.js',
   },
   resolve: {
      alias: {'@': resolvePath('./src')
      },
      extensions: ['.js', '.json', '.ts', '.jsx', '.vue']
   },
   module: {
      rules: [
         {
            test: /\.css$/,
            use: [
               'style-loader',
               {
                  loader: 'css-loader',
                  options: {
                     importLoaders: 1,
                     esModule: false
                  }
               },
               'postcss-loader',
            ]
         },
         {
            test: /\.less$/,
            use: [
               'style-loader',
               'css-loader',
               'postcss-loader',
               'less-loader'
            ]
         },
         {test: /\.(png|jpg|gif)$/,
            type: 'asset',
            generator: {filename: 'imgs/[name].[hash:4][ext]',
            },
            parser: {
               dataUrlCondition: {maxSize: 10 * 1024}
            }
         },
         {test: /\.(woff2?|eot|ttf|otf)$/,
            type: 'asset/resource',      // 图标字体文件,只须要拷贝到 dist 目录即可
            generator: {filename: 'font/[name].[hash:3][ext]'
            }
         },
         {
            test: /\.jsx?$/,
            exclude: /node_modules/, // 排除掉 node_modules 目录下的 js 文件,防止反复填充解决
            use: ['babel-loader'],
         }
      ]
   },
   plugins: [
      new HtmlWebpackPlugin({
         title: 'babel-webpack-plugin',
         template: './public/index.html',
      }),
   ]
}


module.exports = (env) => {
   const isProduction = env.production;
   console.log(new Boolean(isProduction), '<----- isProduction');
   const config = merge(commonConfig, isProduction ? require('./webpack.prod') : require('./webpack.dev'));

   return config;
}


   

生产环境 webpack.prod.js(这里会报错,再解决 ts 的 babel-loader 中,配置了 ts 模块刷新):

const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');


module.exports = {
   mode: 'production',
   plugins: [new CleanWebpackPlugin(),
      new CopyWebpackPlugin({
         patterns: [
            {
               from: 'public',
               // to:'dist', 默认到 output 目录下
               globOptions: {ignore: ['**/index.html'] // 疏忽掉该目录下的 index.html 文件
               }
            }
         ]
      }),
   ]
}

开发环境 webpack.dev.js:

const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin')


module.exports = {
   mode: 'development',
   devtool: 'source-map',
   target: 'web', // 开发阶段屏蔽.browserslistrc
   devServer: {
      compress: true, // 将资源压缩之后,再返回给客户端展现
      port: 5505,    // 端口
      hot: 'only',   // 当某个模块谬误被纠正时,只会更新单个模块,true 时会更新所有模块
      open: false,    // 是否主动关上浏览器
      historyApiFallback: true,   // 当应用前端路由申请后端时,如果路由不存在,应该应用前端路由匹配
   },
   plugins: [new CleanWebpackPlugin(),
      new HtmlWebpackPlugin({
         title: 'babel-webpack-plugin',
         template: './public/index.html',
      }),
      new CopyWebpackPlugin({
         patterns: [
            {
               from: 'public',
               // to:'dist', 默认到 output 目录下
               globOptions: {ignore: ['**/index.html'] // 疏忽掉该目录下的 index.html 文件
               }
            }
         ]
      }),
      new ReactRefreshWebpackPlugin(),]
}
正文完
 0