webpack

webpack 配置别名

  1. 拉取配置文件,安装依赖

    1. yarn eject
    2. yarn install
  2. 配置 别名

    1. alias: {
    2. // Support React Native Web
    3. // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-we
    4. 'react-native': 'react-native-web',
    5. // Allows for better profiling with ReactDevTools
    6. ...(isEnvProductionProfile && {
    7. 'react-dom$': 'react-dom/profiling',
    8. 'scheduler/tracing': 'scheduler/tracing-profiling',
    9. }),
    10. ...(modules.webpackAliases || {}),
    11. // done alias
    12. '@': path.resolve(__dirname, '../src'),
    13. },

    移动端适配 flexible

    参考

  3. 安装 yarn add lib**-**flexible postcss**-**px2rem

  4. 引入 **import** 'lib-flexible'
  5. webpack 中配置
    1. const px2rem = require('postcss-px2rem-exclude')
    1. {
    2. // Options for PostCSS as we reference these options twice
    3. // Adds vendor prefixing based on your specified browser support in
    4. // package.json
    5. loader: require.resolve('postcss-loader'),
    6. options: {
    7. // Necessary for external CSS imports to work
    8. // https://github.com/facebook/create-react-app/issues/2677
    9. ident: 'postcss',
    10. plugins: () => [
    11. require('postcss-flexbugs-fixes'),
    12. require('postcss-preset-env')({
    13. autoprefixer: {
    14. flexbox: 'no-2009',
    15. },
    16. stage: 3,
    17. },
    18. ),
    19. // done config px2rem -- 1rem = 75px (750px)
    20. px2rem({ remUnit: 75, exclude: /node_modules/i }),
    21. // Adds PostCSS Normalize as the reset css with default options,
    22. // so that it honors browserslist config in package.json
    23. // which in turn let's users customize the target behavior as per their needs.
    24. postcssNormalize(),
    25. ],
    26. sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
    27. },
    28. },


    postcss**-**px2rem 中 没有 exclude,改用 postcss**-**px2rem**-**exclude yarn remove postcss**-**px2rem yarn add postcss**-**px2rem**-**exclude

webpack 配置 proxy

  1. devServer: {
  2. port: port,
  3. open: true,
  4. overlay: {
  5. warnings: false,
  6. errors: true
  7. },
  8. proxy: {
  9. '/api': {
  10. target: 'http://000.000.000.000:8088/',
  11. changeOrigin: true,
  12. pathRewrite: {
  13. '^/api': '' // 路径重写
  14. },
  15. logLevel:'debug' // 打印日志
  16. }
  17. }
  18. }

默认 request header 中 origin 为local 本地地址,设置 changeOrigin,origin变为 target 目标地址

去除console

生产环境下去除 console
webpack.prod.config.js 文件下

  1. 安装 yarn add --dev uglifyjs-webpack-plugin
  2. 引入

    1. const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
  3. 在 plugins中配置

    1. plugins: [
    2. new UglifyJsPlugin({
    3. uglifyOptions: {
    4. output: {
    5. comments: false, // 去掉注释
    6. },
    7. warnings: false,
    8. compress: {
    9. drop_console: true,
    10. drop_debugger: false,
    11. pure_funcs: ['console.log']//移除 console
    12. }
    13. }
    14. })
    15. ],

    托管cdn

    webpack.dev.js

    1. const devWebpackConfig = merge(baseWebpackConfig, {
    2. },
    3. plugins: [
    4. new HtmlWebpackPlugin({
    5. filename: 'index.html',
    6. template: 'index.html',
    7. inject: true,
    8. isProd: false
    9. }),
    10. ]
    11. })

    webpack.prod.js

    1. const webpackConfig = merge(baseWebpackConfig, {
    2. entry: {
    3. app: './src/main.prod.js'
    4. },
    5. externals: {
    6. 'vue': 'Vue',
    7. 'element-ui': 'ELEMENT'
    8. },
    9. new HtmlWebpackPlugin({
    10. filename: process.env.NODE_ENV === 'testing'
    11. ? 'index.html'
    12. : config.build.index,
    13. template: 'index.html',
    14. inject: true,
    15. isProd: true, // 配置首页标识
    16. minify: {
    17. removeComments: true,
    18. collapseWhitespace: true,
    19. removeAttributeQuotes: true
    20. // more options:
    21. // https://github.com/kangax/html-minifier#options-quick-reference
    22. },
    23. // necessary to consistently work with multiple chunks via CommonsChunkPlugin
    24. chunksSortMode: 'dependency'
    25. }),
    26. }

    inde.html ```html <!DOCTYPE html>

    <% if (htmlWebpackPlugin.options.isProd) { %> <% } %> <% if (htmlWebpackPlugin.options.isProd) { %> <% } %>
  1. <a name="ZsXan"></a>
  2. ## Vite
  3. <a name="uFP8H"></a>
  4. ### Vite 配置解析别名
  5. 1. 在 vite 配置 别名
  6. ```javascript
  7. import { defineConfig } from 'vite'
  8. import vue from '@vitejs/plugin-vue'
  9. import path from 'path'
  10. export default defineConfig({
  11. plugins: [vue()], // Vue 的插件
  12. resolve: {
  13. alias: {
  14. '@': path.resolve(__dirname, './src')
  15. }
  16. }
  17. })
  1. 配置自动自动补全,别名跳转

    1. {
    2. "compilerOptions": {
    3. "paths": {
    4. "@/*": ["./*"]
    5. }
    6. }
    7. }

    Vite 去除 console

    1. {
    2. build: {
    3. minify: 'terser',
    4. terserOptions: {
    5. compress: {
    6. // 生产环境时移除console
    7. drop_console: true,
    8. drop_debugger: true,
    9. },
    10. },
    11. },
    12. }

    Vue

    vue 配置全局scss

    sass-resources-loader

  2. 安装 sass-resources-loader,yarn add sass-resources-loader -D

  3. 配置vue.config.js

    1. module.exports = {
    2. chainWebpack: config => {
    3. const oneOfsMap = config.module.rule('scss').oneOfs.store
    4. oneOfsMap.forEach(item => {
    5. item
    6. .use('sass-resources-loader')
    7. .loader('sass-resources-loader')
    8. .options({
    9. // Or array of paths
    10. resources: ['./src/assets/scss/_mixins.scss', './src/assets/scss/_variables.scss']
    11. })
    12. .end()
    13. })
    14. }
    15. }

    loaderOptions

  4. 安装 sass,sass-loader,yarn add sass-loader sass --dev

  5. 配置 vue.config.js

    vue 2.6,sass-loader 版本应该为^10,不能过高

  1. module.exports = {
  2. css: {
  3. loaderOptions: {
  4. scss: {
  5. additionalData: `@import "~@/css/variables.scss";@import "~@/css/mixins.scss";`
  6. },
  7. }
  8. }
  9. }

element ui 按需导入

安装 element ui

  1. yarn add element-ui
  2. yarn add babel-plugin-component -D

修改 babel.config.js

  1. module.exports = {
  2. presets: ["@vue/cli-plugin-babel/preset"],
  3. plugins: [
  4. [
  5. "component",
  6. {
  7. libraryName: "element-ui",
  8. styleLibraryName: "theme-chalk",
  9. },
  10. ],
  11. ],
  12. };

Vue 配置别名

vue.config.js

  1. const path = require('path')
  2. function load (url) {
  3. return path.resolve(__dirname, url)
  4. }
  5. module.exports = {
  6. chainWebpack: config => {
  7. config.when(process.env.NODE_ENV === 'production', config => {
  8. config.resolve.alias
  9. .set('@components', load('./src/components'))
  10. .set('@css', load('./src/assets/css'))
  11. .set('@components', load('./src/components'))
  12. .set('@views', load('./src/views'))
  13. .set('@mixins', load('./src/mixins'))
  14. .set('@plugins', load('./src/plugins'))
  15. .set('@static', load('./src/static'))
  16. .set('@utils', load('./src/utils'))
  17. .set('@api', load('./src/api'))
  18. .set('@mock', load('./src/mock'))
  19. .set('@store', load('./src/store'))
  20. }
  21. }

生产开发环境

  1. 新建 .env.development 和 .env.production 文件

    1. VUE_APP_ENV="production"
    1. VUE_APP_ENV="development"
  2. 通过 process.env.VUE_APP_ENV 获取变量

    踩坑:如果设置 NODEENV 和 BASE_URL失效,尝试以 `VUE_APP` 开头

vue引入 font-awesome

  1. 安装 yarn add font-awesome
  2. main.js引入

    1. import 'font-awesome/css/font-awesome.css'

    px to rem

  3. yarn add postcss-pxtorem@^5 --dev

  4. 新建 postcss.config.js
    1. module.exports = {
    2. plugins: {
    3. 'postcss-pxtorem': {
    4. //根元素字体大小
    5. rootValue: 16,
    6. //匹配CSS中的属性,* 代表启用所有属性
    7. propList: ['*'],
    8. //转换成rem后保留的小数点位数
    9. unitPrecision: 5,
    10. //小于12px的样式不被替换成rem
    11. minPixelValue: 12,
    12. exclude: ['node_modules']
    13. }
    14. }
    15. }

    postcss-pxtorem@6 会报错

去除 console

  1. const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
  2. module.exports = {
  3. // 去除生产环境sourceMap
  4. productionSourceMap: false,
  5. configureWebpack: config => {
  6. const plugins = []
  7. if (process.env.NODE_ENV !== 'development') {
  8. plugins.push(
  9. new UglifyJsPlugin({
  10. uglifyOptions: {
  11. output: {
  12. comments: false, // 去掉注释
  13. },
  14. warnings: false,
  15. compress: {
  16. drop_console: true,
  17. drop_debugger: false,
  18. pure_funcs: ['console.log']//移除 console
  19. }
  20. }
  21. })
  22. )
  23. return { plugins }
  24. }
  25. }
  26. }

React

antd 按需导入

  1. 安装 antd yarn add antd
  2. 安装 按需导入插件 yarn add babel-plugin-import -D
  3. 拉取配置文件,然后安装依赖

    1. yarn eject
    2. yarn install
  4. package.json 同级目录下新建 .babelrc(需删除 package.json中 babel配置)内容如下 ```json { “presets”: [“react-app”], “plugins”: [ [ “import”, {

    1. "libraryName": "antd",
    2. "libraryDirectory": "es",
    3. "style": "css"

    } ] ] }

  1. <a name="gT8MS"></a>
  2. ### react 配置全局 scss
  3. 1. 安装 sass `yarn add sass -D`
  4. 1. 安装 全局loader `yarn add sass-resources-loader -D`
  5. 1. 拉取配置文件,安装依赖
  6. ```json
  7. yarn eject
  8. yarn install
  1. 配置 全局sass

    1. {
    2. test: sassRegex,
    3. exclude: sassModuleRegex,
    4. use: getStyleLoaders(
    5. {
    6. importLoaders: 3,
    7. sourceMap: isEnvProduction
    8. ? shouldUseSourceMap
    9. : isEnvDevelopment,
    10. },
    11. 'sass-loader'
    12. ).concat([
    13. // done global scss
    14. {
    15. loader: "sass-resources-loader",
    16. options: {
    17. resources: [
    18. path.join(__dirname, "../src/assets/scss/_variables.scss"),
    19. path.join(__dirname, "../src/assets/scss/_mixins.scss")
    20. ]
    21. }
    22. }
    23. ]),
    24. // Don't consider CSS imports dead code even if the
    25. // containing package claims to have no side effects.
    26. // Remove this when webpack adds a warning or an error for this.
    27. // See https://github.com/webpack/webpack/issues/6571
    28. sideEffects: true,
    29. },

    Nginx

    nginx 配置 history router

    1. server {
    2. listen 80;
    3. server_name localhost;
    4. location / {
    5. root /app;
    6. index index.html;
    7. try_files $uri $uri/ /index.html;
    8. }
    9. error_page 500 502 503 504 /50x.html;
    10. location = /50x.html {
    11. root /usr/share/nginx/html;
    12. }
    13. }

    启动本地服务器

  2. 项目打包:yarn build

  3. 安装serve:yarn global add serve
  4. 启动本地服务:npx serve -s build 或 npx serve -s build

相关包

cross-env

全平台兼容的环境变量命令
作用:自定义 process.env 中变量

  1. "scripts": {
  2. "start": "react-scripts start",
  3. "start:stage": "cross-env REACT_APP_ENV=stage react-scripts start",
  4. "build": "react-scripts build",
  5. "build:stage": "cross-env REACT_APP_ENV=stage react-app-rewired build",
  6. "test": "react-scripts test",
  7. "eject": "react-scripts eject"
  8. }

https://www.npmjs.com/package/cross-env

dotenv

作用:加载 .env 文件

  1. import dotenv from "dotenv"
  2. // https://github.com/motdotla/dotenv#options
  3. dotenv.config()
  4. // 自定义文件
  5. // require('dotenv').config({ path: '/custom/path/to/.env' })
  6. console.log(process.env)

dotenv-cli

作用:用于命令行加载 env 文件

  1. "scripts": {
  2. "start": "react-app-rewired start",
  3. "build:dev": "dotenv -e .env.development react-app-rewired build",
  4. "build:prod": "dotenv -e .env.production react-app-rewired build",
  5. "build:test": "dotenv -e .env.test react-app-rewired build",
  6. "test": "react-app-rewired test",
  7. "eject": "react-scripts eject"
  8. },

https://www.npmjs.com/package/dotenv-cli

相关链接

react—添加环境变量