webpack
webpack 配置别名
拉取配置文件,安装依赖
yarn ejectyarn install
配置 别名
alias: {// Support React Native Web// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-we'react-native': 'react-native-web',// Allows for better profiling with ReactDevTools...(isEnvProductionProfile && {'react-dom$': 'react-dom/profiling','scheduler/tracing': 'scheduler/tracing-profiling',}),...(modules.webpackAliases || {}),// done alias'@': path.resolve(__dirname, '../src'),},
移动端适配 flexible
安装
yarn add lib**-**flexible postcss**-**px2rem- 引入
**import** 'lib-flexible' webpack中配置const px2rem = require('postcss-px2rem-exclude')
{// Options for PostCSS as we reference these options twice// Adds vendor prefixing based on your specified browser support in// package.jsonloader: require.resolve('postcss-loader'),options: {// Necessary for external CSS imports to work// https://github.com/facebook/create-react-app/issues/2677ident: 'postcss',plugins: () => [require('postcss-flexbugs-fixes'),require('postcss-preset-env')({autoprefixer: {flexbox: 'no-2009',},stage: 3,},),// done config px2rem -- 1rem = 75px (750px)px2rem({ remUnit: 75, exclude: /node_modules/i }),// Adds PostCSS Normalize as the reset css with default options,// so that it honors browserslist config in package.json// which in turn let's users customize the target behavior as per their needs.postcssNormalize(),],sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,},},
postcss**-**px2rem中 没有 exclude,改用postcss**-**px2rem**-**excludeyarn remove postcss**-**px2remyarn add postcss**-**px2rem**-**exclude
webpack 配置 proxy
devServer: {port: port,open: true,overlay: {warnings: false,errors: true},proxy: {'/api': {target: 'http://000.000.000.000:8088/',changeOrigin: true,pathRewrite: {'^/api': '' // 路径重写},logLevel:'debug' // 打印日志}}}
默认 request header 中 origin 为local 本地地址,设置 changeOrigin,origin变为 target 目标地址
去除console
生产环境下去除 console
webpack.prod.config.js 文件下
- 安装
yarn add --dev uglifyjs-webpack-plugin 引入
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
在 plugins中配置
plugins: [new UglifyJsPlugin({uglifyOptions: {output: {comments: false, // 去掉注释},warnings: false,compress: {drop_console: true,drop_debugger: false,pure_funcs: ['console.log']//移除 console}}})],
托管cdn
webpack.dev.js
const devWebpackConfig = merge(baseWebpackConfig, {},plugins: [new HtmlWebpackPlugin({filename: 'index.html',template: 'index.html',inject: true,isProd: false}),]})
webpack.prod.js
const webpackConfig = merge(baseWebpackConfig, {entry: {app: './src/main.prod.js'},externals: {'vue': 'Vue','element-ui': 'ELEMENT'},new HtmlWebpackPlugin({filename: process.env.NODE_ENV === 'testing'? 'index.html': config.build.index,template: 'index.html',inject: true,isProd: true, // 配置首页标识minify: {removeComments: true,collapseWhitespace: true,removeAttributeQuotes: true// more options:// https://github.com/kangax/html-minifier#options-quick-reference},// necessary to consistently work with multiple chunks via CommonsChunkPluginchunksSortMode: 'dependency'}),}
inde.html ```html <!DOCTYPE html>
<% if (htmlWebpackPlugin.options.isProd) { %> <% } %> <% if (htmlWebpackPlugin.options.isProd) { %> <% } %>
<a name="ZsXan"></a>## Vite<a name="uFP8H"></a>### Vite 配置解析别名1. 在 vite 配置 别名```javascriptimport { defineConfig } from 'vite'import vue from '@vitejs/plugin-vue'import path from 'path'export default defineConfig({plugins: [vue()], // Vue 的插件resolve: {alias: {'@': path.resolve(__dirname, './src')}}})
配置自动自动补全,别名跳转
{"compilerOptions": {"paths": {"@/*": ["./*"]}}}
Vite 去除 console
{build: {minify: 'terser',terserOptions: {compress: {// 生产环境时移除consoledrop_console: true,drop_debugger: true,},},},}
Vue
vue 配置全局scss
sass-resources-loader
安装 sass-resources-loader,
yarn add sass-resources-loader -D配置
vue.config.jsmodule.exports = {chainWebpack: config => {const oneOfsMap = config.module.rule('scss').oneOfs.storeoneOfsMap.forEach(item => {item.use('sass-resources-loader').loader('sass-resources-loader').options({// Or array of pathsresources: ['./src/assets/scss/_mixins.scss', './src/assets/scss/_variables.scss']}).end()})}}
loaderOptions
安装 sass,sass-loader,
yarn add sass-loader sass --dev- 配置
vue.config.jsvue 2.6,sass-loader 版本应该为^10,不能过高
module.exports = {css: {loaderOptions: {scss: {additionalData: `@import "~@/css/variables.scss";@import "~@/css/mixins.scss";`},}}}
element ui 按需导入
安装 element ui
yarn add element-uiyarn add babel-plugin-component -D
修改 babel.config.js
module.exports = {presets: ["@vue/cli-plugin-babel/preset"],plugins: [["component",{libraryName: "element-ui",styleLibraryName: "theme-chalk",},],],};
Vue 配置别名
vue.config.js
const path = require('path')function load (url) {return path.resolve(__dirname, url)}module.exports = {chainWebpack: config => {config.when(process.env.NODE_ENV === 'production', config => {config.resolve.alias.set('@components', load('./src/components')).set('@css', load('./src/assets/css')).set('@components', load('./src/components')).set('@views', load('./src/views')).set('@mixins', load('./src/mixins')).set('@plugins', load('./src/plugins')).set('@static', load('./src/static')).set('@utils', load('./src/utils')).set('@api', load('./src/api')).set('@mock', load('./src/mock')).set('@store', load('./src/store'))}}
生产开发环境
新建
.env.development和.env.production文件VUE_APP_ENV="production"
VUE_APP_ENV="development"
通过
process.env.VUE_APP_ENV获取变量踩坑:如果设置 NODEENV 和 BASE_URL失效,尝试以 `VUE_APP` 开头
vue引入 font-awesome
- 安装
yarn add font-awesome main.js引入import 'font-awesome/css/font-awesome.css'
px to rem
yarn add postcss-pxtorem@^5 --dev- 新建
postcss.config.jsmodule.exports = {plugins: {'postcss-pxtorem': {//根元素字体大小rootValue: 16,//匹配CSS中的属性,* 代表启用所有属性propList: ['*'],//转换成rem后保留的小数点位数unitPrecision: 5,//小于12px的样式不被替换成remminPixelValue: 12,exclude: ['node_modules']}}}
postcss-pxtorem@6 会报错
去除 console
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')module.exports = {// 去除生产环境sourceMapproductionSourceMap: false,configureWebpack: config => {const plugins = []if (process.env.NODE_ENV !== 'development') {plugins.push(new UglifyJsPlugin({uglifyOptions: {output: {comments: false, // 去掉注释},warnings: false,compress: {drop_console: true,drop_debugger: false,pure_funcs: ['console.log']//移除 console}}}))return { plugins }}}}
React
antd 按需导入
- 安装 antd
yarn add antd - 安装 按需导入插件
yarn add babel-plugin-import -D 拉取配置文件,然后安装依赖
yarn ejectyarn install
package.json同级目录下新建.babelrc(需删除 package.json中 babel配置)内容如下 ```json { “presets”: [“react-app”], “plugins”: [ [ “import”, {"libraryName": "antd","libraryDirectory": "es","style": "css"
} ] ] }
<a name="gT8MS"></a>### react 配置全局 scss1. 安装 sass `yarn add sass -D`1. 安装 全局loader `yarn add sass-resources-loader -D`1. 拉取配置文件,安装依赖```jsonyarn ejectyarn install
配置 全局sass
{test: sassRegex,exclude: sassModuleRegex,use: getStyleLoaders({importLoaders: 3,sourceMap: isEnvProduction? shouldUseSourceMap: isEnvDevelopment,},'sass-loader').concat([// done global scss{loader: "sass-resources-loader",options: {resources: [path.join(__dirname, "../src/assets/scss/_variables.scss"),path.join(__dirname, "../src/assets/scss/_mixins.scss")]}}]),// Don't consider CSS imports dead code even if the// containing package claims to have no side effects.// Remove this when webpack adds a warning or an error for this.// See https://github.com/webpack/webpack/issues/6571sideEffects: true,},
Nginx
nginx 配置 history router
server {listen 80;server_name localhost;location / {root /app;index index.html;try_files $uri $uri/ /index.html;}error_page 500 502 503 504 /50x.html;location = /50x.html {root /usr/share/nginx/html;}}
启动本地服务器
项目打包:
yarn build- 安装serve:
yarn global add serve - 启动本地服务:
npx serve -s build或npx serve -s build
相关包
cross-env
全平台兼容的环境变量命令
作用:自定义 process.env 中变量
"scripts": {"start": "react-scripts start","start:stage": "cross-env REACT_APP_ENV=stage react-scripts start","build": "react-scripts build","build:stage": "cross-env REACT_APP_ENV=stage react-app-rewired build","test": "react-scripts test","eject": "react-scripts eject"}
https://www.npmjs.com/package/cross-env
dotenv
作用:加载 .env 文件
import dotenv from "dotenv"// https://github.com/motdotla/dotenv#optionsdotenv.config()// 自定义文件// require('dotenv').config({ path: '/custom/path/to/.env' })console.log(process.env)
dotenv-cli
作用:用于命令行加载 env 文件
"scripts": {"start": "react-app-rewired start","build:dev": "dotenv -e .env.development react-app-rewired build","build:prod": "dotenv -e .env.production react-app-rewired build","build:test": "dotenv -e .env.test react-app-rewired build","test": "react-app-rewired test","eject": "react-scripts eject"},
https://www.npmjs.com/package/dotenv-cli
