首页
更多应用
Search
1
修改iview的标签为i-的形式而不是驼峰的形式
2,727 阅读
2
PHP微信和企业微信签名
2,414 阅读
3
在VUE中怎么全局引入sass文件
2,174 阅读
4
vscode硬件占用较高解决方案
1,907 阅读
5
解决Macos下storm系列IDE卡顿的问题
1,850 阅读
默认分类
JS
VUE
CSS
mac使用技巧
React
fastmock
登录
/
注册
Search
标签搜索
react
js
vue
nodejs
vscode
项目
代码
webpack
工具
nginx
小程序
css
fastmock
http
vue-cli3
eslint
git
浏览器
const
true
fastmock技术社区
累计撰写
95
篇文章
累计收到
9
条评论
首页
栏目
默认分类
JS
VUE
CSS
mac使用技巧
React
fastmock
页面
更多应用
搜索到
3
篇与
的结果
2022-11-23
webpack5.x+React18搭建移动端项目
webpack5.x+React18搭建移动端项目项目仓库地址 https://github.com/MarvenGong/webpack5-react18-ts-basic在项目开发中,每开始一个新项目我都是使用现有的脚手架,这非常便于快速地启动一个新项目,而且通用的脚手架通常考虑地更加全面,也有利于项目的稳定开发;不过对于一个小项目,根据需求自己搭建可能会更好,一方面小项目不需要脚手架那么丰富的功能,另一方面可以提高对项目的掌控度以方便后期的扩展本项目基于公司内一个移动端项目搭建,旨在搭建一个快速,高效,灵活的前端开发环境。项目中使用了最新版本的webpack构建工具,最新版本的react前段框架和react-router6.x特性搭建,通过本项目,可以可以熟悉和巩固以下基础技能webpack5构建原理和基本配置,以及打包性能的提升和使用方法react18的feature,如,根组件的创建方式等const root = createRoot(document.getElementById('root') as Element); root.render(<RouterProvider router={router} />);react-router6 的新特性和单文件路由的使用方式wecpack5 中配置移动端响应式方案 rem布局的方法其他webpack插件和loader的使用项目仓库地址 https://github.com/MarvenGong/webpack5-react18-ts-basic接下来,详细说明项目中的各个配置环境webpack5的一个重要特性,会根据配置的mode属性是develop还是production来判断是否需要开启构建优化,这个优化过程是指对构建产品的优化,如js uglify,压缩,tree-shaking 等等,所以,我们的开发环境,是可以不用用到那些优化操作的,那么就需要把mode指定成 develop 这样可以在我们保存代码后,获得更快的热更新速度,我这里为了简单,直接在npm script中制定env,在webpack.js中使用package.json 中的scripts"scripts": { "serve": "cross-env NODE_ENV=development webpack serve --config webpack.config.js", "dev": "npm run serve", },PS: 切忌在NODE_ENV=development顺手写上&&写上了就设置不上了webpack.config.js 中使用环境变量const isDev = process.env.NODE_ENV === 'development'; mode: isDev ? 'development' : 'production',基础配置1、entry入口,配置webpack构建的入口文件我这里使用了package.json 中的name属性的值作为主文件的名称entry: { [packageJson?.name]: path.resolve(__dirname, './src/app.tsx'), },2、output 制定输出文件路径和文件名output: { // 开发环境不使用hash文件名 filename: isDev ? '[name].js' : '[name].[hash].js', path: path.resolve(__dirname, './dist'), publicPath: '/', clean: true, // 输出文件前会先清空目标目录的文件 },3、stats 指定webpack在控制台的输出内容stats: { all: false, assets: true, errors: true, assetsSort: '!size', // 按照文件大小倒序 entrypoints: true, modules: false, assetsSpace: 1000, preset: 'minimal', },4、devServer 配置本地开发服务器,如端口,代理等,此处不做详细说明,5、devtool 制定sourcemap文件生成方式devtool: isDev ? 'inline-source-map' : 'source-map', // 开发环境直接打包到js文件中,现网环境打包到独立文件,我的处理方式是在自动化部署工具中将sourcemap文件保存到特定地方,线上排查的时候使用6、resolve 配置6-1 extensions 指定webpack需要处理的文件扩展名类型6-2 alias 路径别名,注意要去 tsconfig 中相应配置,否则代码中会报ts错误项目使用的loader处理module说明ts-loader 处理typescript 语法以及es6特性(包含了babel-loader)style-loader 处理样式资源到html中,开发环境使用MiniCssExtractPlugin.loader 处理样式资源到单独的样式文件中,生产环境使用css-loader 让我们可以在js(x)或者ts(x)中使用import语句导入样式文件 如 import ‘./style.less’postcss-loader 对css进行编译处理,本项目主要用来处理 px2rem 将我们的样式中的px转为rem(只能针对import导入的样式文件,行内样式不生效)less-loader less编译为cssurl-loader 处理图片和字体等资源,小于limit则编码,大于则处理路径,包含了 file-loader(file-loader 主要作用是使我们可以在js(x)或者ts(x)中使用import语句导入静态资源文件 import ‘./xxx.png’)使用到的plugins做打包后处理说明copy-webpack-plugin 拷贝 public下的静态资源到 dist 目录clean-webpack-plugin 清理打包目标目录,防止重复文件WebpackBar 美化打包进度显示的插件HtmlWebpackPlugin 处理我们的构建产物到指定的html中,重中之重MiniCssExtractPlugin 压缩我们的css文件,只在生产环境使用好了,有了上面的介绍,就可以直接看我们的webpack配置文件了主webpack.config.js// @ts-nocheck const path = require('path'); const tsImportPluginFactory = require('ts-import-plugin'); const SpeedMeasurePlugin = require('speed-measure-webpack-plugin'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const smp = new SpeedMeasurePlugin(); const fs = require('fs'); const packageJson = require('./package.json'); const optimization = require('./webpack-configs/optimization'); const config = require('./webpack-configs/config'); const plugins = require('./webpack-configs/plugins'); const isDev = process.env.NODE_ENV === 'development'; const SMP_SWICTH = false; console.log('-------当前环境-------', process.env.NODE_ENV); const wrapConfig = (isDev && SMP_SWICTH) ? smp.wrap : (config) => config; module.exports = wrapConfig({ target: 'web', mode: isDev ? 'development' : 'production', entry: { [packageJson?.name]: path.resolve(__dirname, './src/app.tsx'), }, output: { filename: isDev ? '[name].js' : '[name].[hash].js', path: path.resolve(__dirname, './dist'), publicPath: '/', clean: true, }, // infrastructureLogging: { // level: 'error' // }, stats: { all: false, assets: true, errors: true, assetsSort: '!size', entrypoints: true, modules: false, assetsSpace: 1000, preset: 'minimal', }, devServer: { ...config.dev, historyApiFallback: true, // static: { // directory: path.join(__dirname, './public'), // }, watchFiles: './src/**/*', }, devtool: isDev ? 'inline-source-map' : 'source-map', resolve: { alias: { '@src': path.resolve(__dirname, './src'), '@tea/app': path.resolve(__dirname, './app'), }, extensions: ['.ts', '.tsx', '.js', 'less'], }, module: { rules: [ { test: /\.(jsx|tsx|js|ts)$/, loader: 'ts-loader', options: { transpileOnly: true, getCustomTransformers: () => ({ before: [ tsImportPluginFactory([ { style: false, libraryName: 'lodash', libraryDirectory: null, camel2DashComponentName: false, }, { style: true }, ]), ], }), compilerOptions: { module: 'esnext', }, }, exclude: /node_modules/, }, { test: /\.(le|c)ss$/, use: [ isDev ? 'style-loader' : MiniCssExtractPlugin.loader, // 现网环境才提取css到一个文件中 { loader: 'css-loader', // 使用import语句导入样式 }, { loader: "postcss-loader", options: { postcssOptions: { config: './postcss.config.js', }, sourceMap: true, } }, { loader: 'less-loader', // 转less为css options: { lessOptions: { modifyVars: { '@body-background': '#f5f5f5', }, javascriptEnabled: true, }, }, }, // { // loader: 'style-resources-loader', // options: { // patterns: path.resolve(__dirname, './src/styles/common.less'), // 全局引入公共的scss 文件 // }, // }, ], }, { test: /\.(png|jp(e)?g|gif|woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/, use: [ { loader: 'url-loader', // 处理图片和字体等资源,小于limit则编码,大于则处理路径,包含了 file-loader options: { limit: 8192, }, }, ], }, ], }, watchOptions: { // 设置不监听的⽂件或⽂件夹,默认为空 ignored: /node_modules/, // ⽂件改变不会⽴即执⾏,⽽是会等待300ms之后再去执⾏ aggregateTimeout: 300, // 原理是轮询系统⽂件有⽆变化再去更新的,默认1秒钟轮询1000次 poll: 1000, }, plugins, optimization: !isDev ? optimization : {}, }); 在根目录下的wenpack-configs 目录中的下面三个拆出来的jswebpack 插件配置 plugins.jsconst path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const WebpackBar = require('webpackbar'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const chalk = require('chalk'); const webpack = require('webpack'); const isDev = process.env.NODE_ENV === 'development'; const config = require('./config'); module.exports = [ new CopyWebpackPlugin({ patterns: [ { from: path.resolve(__dirname, '../public/px2rem-hike.js') } ], }), new CleanWebpackPlugin({ dry: false, // 是否打印删除的内容 }), // 热更新替换 new webpack.HotModuleReplacementPlugin(), // @ts-ignore new WebpackBar({ name: '能碳工场移动端h5', color: '#0049b0', // 默认green,进度条颜色支持HEX basic: true, // 默认true,启用一个简单的日志报告器 reporter: { change() { console.log(chalk.blue.bold('文件修改,重新编译...')); }, afterAllDone(context) { console.log(chalk.bgBlue.white(' 能碳工场移动端 ') + chalk.green(' 编译完成')); isDev && console.log(chalk.bgBlue.white(' 能碳工场移动端 ') + chalk.green(' 开发预览地址:http://127.0.0.1:' + config.dev.port)) }, }, }), new HtmlWebpackPlugin({ minify: false, chunks: 'all', template: path.resolve(__dirname, '../public/index.html'), filename: 'index.html' }), new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn|ja|ko/), ].concat(isDev ? [] : [new MiniCssExtractPlugin({ filename: '[name].[hash].css', })])webpack优化配置 optimization.jsconst CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); module.exports = { minimize: true, minimizer: [ new CssMinimizerPlugin(), '...' // 压缩css 和 js ], splitChunks: { chunks: 'async', cacheGroups: { defaultVendors: { test: /[\\/]node_modules[\\/]/, priority: -10, reuseExistingChunk: true, }, default: { minChunks: 2, priority: -20, reuseExistingChunk: true, }, }, }, }; 其他常用需要修改配置 config.jsmodule.exports = { dev: { host: '0.0.0.0', port: 10010, hot: true, open: false, client: { overlay: { errors: true, warnings: false, }, }, proxy: { '/api': { // logLevel: 'debug', changeOrigin: true, pathRewrite: { '^/api': '' }, target: 'http://30.168.123.79', }, }, } };
2022年11月23日
357 阅读
0 评论
1 点赞
2021-01-27
React 开发常用 eslint + Prettier vscode 配置方案
1、安装 vscode 插件 eslint 和 Prettier要知道 eslint 和 Prettier 所做的事情都是基于编辑器支持的,所以我们做的所有的事情基本都是做给编辑器看的,配置的所有参数配置也是为了编辑器配置的。2、设置 vscode 让其支持保存自动格式化、支持 React 语法2、项目安装npm依赖包 这些包都可以安装到 devDependencies 也就是 npm i -D XXX 或者 yarn add -D XXX# eslint库 eslint # 处理tsx类型的文件和react语法 eslint-plugin-react # 加载外部解析器,用来处理eslint内置的nodejs解析器无法识别的实验性语法,如 static修饰符等,若没有使用ts就安装 @babel/eslint-parser @typescript-eslint/parser其他依赖可以根据eslint控制台提示需要什么就装什么.eslintrc.js 配置文件内容module.exports = { root: true, env: { browser: true, mocha: true, node: true, es6: true, commonjs: true }, plugins: [ 'react' ], parser: '@typescript-eslint/parser', // 若没有使用ts这里配置 @babel/eslint-parser parserOptions: { "requireConfigFile": false, sourceType: 'module', 'ecmaFeatures': { 'experimentalObjectRestSpread': true, 'jsx': true }, ecmaVersion: 2015 }, extends: [ 'eslint:recommended' ], rules: { 'react/jsx-filename-extension': [ 'error', { extensions: ['.js', '.jsx', '.ts', '.tsx'] } ], 'class-methods-use-this': 0, 'jsx-a11y/anchor-is-valid': 0, 'import/extensions': ['off', 'never'], 'quotes': [2, 'single'], //单引号 'no-console': 0, //不禁用console 'no-debugger': 2, //禁用debugger 'no-var': 0, //对var警告 'semi': 0, //不强制使用分号 'no-irregular-whitespace': 0, //不规则的空白不允许 'no-trailing-spaces': 1, //一行结束后面有空格就发出警告 'eol-last': 0, //文件以单一的换行符结束 'no-unused-vars': [1, {'vars': 'all', 'args': 'after-used'}], //不能有声明后未被使用的变量或参数 'no-underscore-dangle': 0, //标识符不能以_开头或结尾 'no-alert': 2, //禁止使用alert confirm prompt 'no-lone-blocks': 0, //禁止不必要的嵌套块 'no-class-assign': 2, //禁止给类赋值 'no-cond-assign': 2, //禁止在条件表达式中使用赋值语句 'no-const-assign': 2, //禁止修改const声明的变量 'no-delete-var': 2, //不能对var声明的变量使用delete操作符 'no-dupe-keys': 2, //在创建对象字面量时不允许键重复 'no-duplicate-case': 2, //switch中的case标签不能重复 'no-dupe-args': 2, //函数参数不能重复 'no-empty': 2, //块语句中的内容不能为空 'no-func-assign': 2, //禁止重复的函数声明 'no-invalid-this': 0, //禁止无效的this,只能用在构造器,类,对象字面量 'no-redeclare': 2, //禁止重复声明变量 'no-spaced-func': 2, //函数调用时 函数名与()之间不能有空格 'no-this-before-super': 0, //在调用super()之前不能使用this或super 'no-undef': 2, //不能有未定义的变量 'no-use-before-define': 0, //未定义前不能使用 'camelcase': 0, //强制驼峰法命名 'jsx-quotes': [2, 'prefer-double'], //强制在JSX属性(jsx-quotes)中一致使用双引号 'react/display-name': 0, //防止在React组件定义中丢失displayName 'react/forbid-prop-types': [2, {'forbid': ['any']}], //禁止某些propTypes 'react/jsx-boolean-value': 2, //在JSX中强制布尔属性符号 'react/jsx-closing-bracket-location': 1, //在JSX中验证右括号位置 'react/jsx-curly-spacing': [2, {'when': 'never', 'children': true}], //在JSX属性和表达式中加强或禁止大括号内的空格。 'react/jsx-indent-props': [2, 2], //验证JSX中的props缩进 'react/jsx-key': 2, //在数组或迭代器中验证JSX具有key属性 'react/jsx-max-props-per-line': [1, {'maximum': 1}], // 限制JSX中单行上的props的最大数量 'react/jsx-no-bind': 0, //JSX中不允许使用箭头函数和bind 'react/jsx-no-duplicate-props': 2, //防止在JSX中重复的props 'react/jsx-no-literals': 0, //防止使用未包装的JSX字符串 'react/jsx-no-undef': 1, //在JSX中禁止未声明的变量 'react/jsx-pascal-case': 0, //为用户定义的JSX组件强制使用PascalCase 'react/jsx-sort-props': 2, //强化props按字母排序 'react/jsx-uses-react': 1, //防止反应被错误地标记为未使用 'react/jsx-uses-vars': 2, //防止在JSX中使用的变量被错误地标记为未使用 'react/no-danger': 0, //防止使用危险的JSX属性 'react/no-did-mount-set-state': 0, //防止在componentDidMount中使用setState 'react/no-did-update-set-state': 1, //防止在componentDidUpdate中使用setState 'react/no-direct-mutation-state': 2, //防止this.state的直接变异 'react/no-multi-comp': 2, //防止每个文件有多个组件定义 'react/no-set-state': 0, //防止使用setState 'react/no-unknown-property': 2, //防止使用未知的DOM属性 'react/prefer-es6-class': 2, //为React组件强制执行ES5或ES6类 'react/prop-types': 0, //防止在React组件定义中丢失props验证 'react/react-in-jsx-scope': 2, //使用JSX时防止丢失React 'react/self-closing-comp': 0, //防止没有children的组件的额外结束标签 'react/sort-comp': 2, //强制组件方法顺序 'no-extra-boolean-cast': 0, //禁止不必要的bool转换 'react/no-array-index-key': 0, //防止在数组中遍历中使用数组key做索引 'react/no-deprecated': 1, //不使用弃用的方法 'react/jsx-equals-spacing': 2, //在JSX属性中强制或禁止等号周围的空格 'no-unreachable': 1, //不能有无法执行的代码 'comma-dangle': 2, //对象字面量项尾不能有逗号 'no-mixed-spaces-and-tabs': 0, //禁止混用tab和空格 'prefer-arrow-callback': 0, //比较喜欢箭头回调 'arrow-parens': 0, //箭头函数用小括号括起来 'arrow-spacing': 0 //=>的前/后括号 } // allow paren-less arrow functions };
2021年01月27日
438 阅读
0 评论
0 点赞
2019-05-17
vscode中支持vue-cli3构建的项目eslint对vue文件的检测
在vue-cli中为了能让vscode能提示.vue文件中的js代码,我们引入了eslint-plugin-html这个eslint插件(使用方法参考VSCode环境下配置ESLint 对Vue单文件的检测)最近开始使用vue-cli3构建项目,主要目的是为了简化项目代码结构和提高编译性能。当我们使用以前的方案去实现vscode对.vue文件的eslint检测时却发现始终无法识别,而且提示以下内容提示信息很容易理解,eslint没有把当前文件当做vue文件处理,而是当做了普通的js文件处理,当然,js文件的外层代码肯定不能含有html标记。最后,我们找到了eslint-plugin-vue,这个插件能完美处理.vue文件,而且还预置了很多可复用的rules(eslint规则)。使用方法如下:第一步: npm install --save-dev eslint-plugin-vue 安装eslint vue支持插件第二步: .eslintrc.js文件中添加plugin说明注:vue-cli3默认不会在根目录创建.eslintrc.js文件,因为vue-cli3除了这种方法配置eslint以外还可以在package.json中通过eslintConfig属性去配置,但是这种方式需要严格遵守json语法规则,我们建议如果您的eslint配置较为复杂,还是在根目录自己创建一个.eslintrc.js文件,这样就可以按照js语法规则去写配置项,也方便注释module.exports = { // ...其他配置项 plugins: [ 'vue' ] // ...其他配置项 }第三步:使用eslint-plugin-vue中预置的eslint规则让其支持.vue文件的基本结构和通用语法规则增加一个文件检测说明配置extends: [ module.exports = { root: true, // https://github.com/standard/standard/blob/master/docs/RULES-en.md extends: [ 'plugin:vue/base' ], }这里我们使用的是base里面的规则,更多的预置规则可以参考文档(eslint-plugin-vue Available rules)[https://eslint.vuejs.org/rules/]关于eslint规则复用可以参考文档https://cn.eslint.org/docs/developer-guide/shareable-configs第四步:如果配置中最外层已经存在解析器说明配置parser: 'babel-eslint',将其移至parserOptions中module.exports = { root: true, parserOptions: { parser: 'babel-eslint', sourceType: 'module' } // ...其他配置项 }第五步:vscode中添加对vue文件支持的设置让vscode可以高亮vue文件中的js代码eslint问题代码"eslint.validate": [ "javascript", "javascriptreact", { "language": "vue", "autoFix": true } ] 附完整的.eslintrc.js文件// https://eslint.org/docs/user-guide/configuring module.exports = { root: true, parserOptions: { parser: 'babel-eslint', sourceType: 'module' }, env: { browser: true }, // https://github.com/standard/standard/blob/master/docs/RULES-en.md extends: [ 'plugin:vue/base' ], // required to lint *.vue files plugins: [ 'vue' ], // add your custom rules here 'rules': { // allow paren-less arrow functions 'indent': [2, 2], // 两个空格的缩进 'quotes': [2, 'single'], // js必须使用单引号 'linebreak-style': [2, 'unix'], // 换行风格 unix/windows 'semi': [2, 'always'], // 语句强制分号结尾 'no-console': [1], // 不允许console语句 'no-unused-vars': [1], // 声明了变量但是没有使用检测 'space-unary-ops': [1, { 'words': true, 'nonwords': false }], // 一元运算符的前/后要不要加空格 'brace-style': [2, '1tbs', { 'allowSingleLine': false }], // 大括号风格 'comma-spacing': [2, { 'before': false, 'after': true }], // 逗号后有空格,前没有空格 'comma-style': [2, 'last'], // 逗号跟在结尾 'key-spacing': [2, { 'beforeColon': false, 'afterColon': true }], // 对象字面量中冒号的前后空格 'lines-around-comment': [ // 行前/行后备注 2, { 'beforeBlockComment': false, // 段注释的前后 'beforeLineComment': false, // 行注释的前面 'afterBlockComment': false, // 块注释的后面 'afterLineComment': false, // 行注释的后面 'allowBlockStart': true, 'allowObjectStart': true, 'allowArrayStart': true }], 'max-depth': [2, 4], // 代码最多允许4层嵌套 'max-len': [1, 160, 2], 'max-nested-callbacks': [2, 3], // 回调嵌套深度 'max-params': [2, 5], // 函数最多只能有5个参数 'max-statements': [1, 80], // 单个函数最多80条语句 'no-array-constructor': [2], // 禁止使用数组构造器 'no-lonely-if': 2, // // 禁止else语句内只有if语句 'no-multiple-empty-lines': [2, { 'max': 3, 'maxEOF': 1 }], // 空行最多不能超过2行 'no-nested-ternary': 2, // 不使用嵌套的三元表达式 'no-spaced-func': 2, // 函数调用时 函数名与()之间不能有空格 'no-trailing-spaces': 2, // 一行结束后面不要有空格 'no-unneeded-ternary': 2, // 禁止不必要的嵌套 var isYes = answer === 1 ? true : false;简单的判断用三元表达式代替 'object-curly-spacing': [2, 'always', { // 大括号内是否允许不必要的空格 always始终允许;never始终不允许 'objectsInObjects': false, 'arraysInObjects': false }], 'arrow-spacing': 2, // =>的前/后括号 'block-scoped-var': 2, // 块语句中使用var 'no-dupe-class-members': 2, // 'no-var': 1, // 禁用var,用let和const代替 'object-shorthand': [1, 'always'], // 强制对象字面量缩写语法 'array-bracket-spacing': [2, 'never'], // 是否允许非空数组里面有多余的空格 'operator-linebreak': [2, 'after'], // 换行时运算符在行尾还是行首 'semi-spacing': [2, { 'before': false, 'after': true }], // 分号前后空格 'keyword-spacing': ['error'], 'space-before-blocks': 2, // 不以新行开始的块{前面要不要有空格 'block-spacing': [2, 'always'], 'space-before-function-paren': [2, 'never'], // 函数定义时括号前面要不要有空格 'space-in-parens': [2, 'never'], // 小括号里面要不要有空格 'spaced-comment': [1, 'always', { 'exceptions': ['-', '*', '+'] }], // 注释风格要不要有空格什么的 'arrow-parens': 0, // allow async-await 'generator-star-spacing': 0, // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 }, globals: { '$': false, 'jquery': false, 'ActiveXObject': false, 'arbor': true, 'layer': false } };
2019年05月17日
838 阅读
0 评论
0 点赞