Vue3 TSX Mobile Terminal Project Based on Vue Cli4 (II)
In the last article we covered project creation, differentiating multi-environment configurations, and integrating the ERuda mobile debugging tool. In this article, we will carry out the configuration of mobile adaptive, HardSource development build acceleration, babel-plugin-import on demand, ESLint, stylelint.
Mobile adaptive
Conventional scheme
There are generally two schemes for mobile terminal adaptation:
-
Px2rem: CSS3’s REM is a unit of size calculated based on the font size of the root element, so rem’s responsive layout is achieved by changing the FONT size of the HTML. Normally we change the font size of the root element based on the screen width using JS, such as lib-flexible/ Flexible package and postCSS-pxtorem plugin.
-
Px2vw: The advanced version of PX2REM converts px units in our CSS to VW. It does not need to dynamically set the font size of the root element and can change in real time according to the screen width. The disadvantage is that it is not as good as REM in compatibility. However, the current performance of PX2VW has basically met the use requirements of most devices, so I will still adopt PX2VW as the mobile terminal adaptive scheme.
Install dependencies
Run NPM install -d postcss-px-to-viewport on the terminal to install the required dependencies
Those who qualify NPM install -d Postcss-px-to-viewport NPM WARN [email protected] requires a peer of Postcs@^ 8.0.0 but none is You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but None is installed. You must install peer dependencies yourself. NPM WARN [email protected] requires A peer of postcss@^8.1.0 but none is installed. You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed. You must install peer Dependencies Yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed Must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but None is installed. You must install peer dependencies yourself. + [email protected] added 1 package from 1 contributorin6.076 sCopy the code
Configuration PostCss
We in vue. Config. Introducing postcss js – px – to – viewport plug-in, and then in the CSS. LoaderOptions. New plugin postcss, converting all the px project in vw, the default design width to 750 px.
Here I’ve also globally introduced a style file common. SCSS in css.loaderoptions. sass to hold some global styles.
According to the following configuration, the subsequent development only needs to set the width of the design drawing to 750px, and the development can be carried out in accordance with the value shown in the design drawing
// Get the environment configuration
const cfg = require("./config/index") ();const Pxtovw = require("postcss-px-to-viewport");
module.exports = {
devServer: {
host: cfg.buildtime.origin_server.ip,
port: cfg.buildtime.origin_server.port,
},
chainWebpack: (config) = > {
// HTML template injection configuration
config.plugin("html").tap((args) = > {
// Embed environment configuration script
const configScript = ` <! --configArea--><script>window.CUSTOMCONFIG =The ${JSON.stringify(
config.runtime
)}</script><! --endOfConfigArea-->`;
args[0].config = configScript;
// Inject erUDA in non-local development and production environments
if(! ["local"."production"].includes(cfg.runtime.env)) {
const erudaCDN = "/ / cdn.bootcdn.net/ajax/libs/eruda/2.4.1/eruda.min.js";
const erudaDomCDN = "/ / cdn.jsdelivr.net/npm/[email protected]";
const erudaScript = ` <! --erudaArea--> <script src="${erudaCDN}"></script>
<script src="${erudaDomCDN}"></script> <script> eruda.init({ tool: ['console', 'network', 'elements', 'resources', 'snippets', 'sources'], }); eruda.add(erudaDom); </script> <! --endOfRrudaArea-->`;
args[0].eruda = erudaScript;
}
return args;
});
},
css: {
loaderOptions: {
// Globally introduce common.scss
sass: {
prependData: '@import "~@/assets/styles/common.scss"; ',},/ / configuration px2vw
postcss: {
plugins: [
new Pxtovw({
unitToConvert: "px".// The unit to convert, default is "px";
viewportWidth: 750.// The viewport width of the design draft
unitPrecision: 5.// The number of decimal places reserved after the unit conversion
propList: ["*"].// List of attributes to be converted,* means match all,! Does not convert
viewportUnit: "vw".// The converted viewport unit
fontViewportUnit: "vw".// The viewport unit used for the converted font
selectorBlackList: [].// CSS selectors without conversion continue to use the original unit
minPixelValue: 1.// Set the minimum conversion value
mediaQuery: false.// Set whether the unit in media query needs to be converted
replace: true.// Whether to replace the attribute value directly without adding the standby attribute
exclude: [/node_modules/].// Ignore files in certain folders}),],},},},},};Copy the code
Effect of the test
SRC /views/ home.vue add class=” Logo “to the vue Logo, and then add width: 600px to the.logo in style.
The screen width we configured above is 750px. So the logo width: 600px translates to 80vw. When we run the project again, we can see that the width of the Logo image has been converted to 80VW.
HardSource development build acceleration
Each project gets bigger and slower to package as the business changes. In the previous webPack DLL dynamic link library scheme can be described as a classic scheme used by many people, but with the upgrade of Webpack, packaging performance has gradually improved a lot, we also hope to reduce the complex relationship brought by configuration, so the optimization of minimal configuration, is necessarily the best choice.
The hard-source-webpack-plugin is a good alternative to the Webpack Dll, which provides an intermediate caching step for modules. The second build will be significantly faster. So HERE I use the hard-source-webpack-plugin as a package optimization solution instead of DLL.
Install dependencies
npm install -D hard-source-webpack-plugin
Those who qualify NPM install -d hard-source-webpack-plugin NPM WARN [email protected] requires a peer of postcss@^8.0.0 but none is You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but None is installed. You must install peer dependencies yourself. NPM WARN [email protected] requires A peer of postcss@^8.1.0 but none is installed. You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed. You must install peer Dependencies Yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed Must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but None is installed. You must install peer dependencies yourself. + [email protected] added 17 packages from 4 contributorsin8.192 sCopy the code
Configuration HardSourceWebpackPlugin
The HardSourceWebpackPlugin is easy to configure, just add it to configureWebpack.plugins.
// Get the environment configuration
const cfg = require("./config/index") ();const Pxtovw = require("postcss-px-to-viewport");
const HardSourceWebpackPlugin = require("hard-source-webpack-plugin");
module.exports = {
devServer: {
host: cfg.buildtime.origin_server.ip,
port: cfg.buildtime.origin_server.port,
},
chainWebpack: (config) = > {
// HTML template injection configuration
config.plugin("html").tap((args) = > {
// Embed environment configuration script
const configScript = ` <! --configArea--><script>window.CUSTOMCONFIG =The ${JSON.stringify(
config.runtime
)}</script><! --endOfConfigArea-->`;
args[0].config = configScript;
// Inject erUDA in non-local development and production environments
if(! ["local"."production"].includes(cfg.runtime.env)) {
const erudaCDN = "/ / cdn.bootcdn.net/ajax/libs/eruda/2.4.1/eruda.min.js";
const erudaDomCDN = "/ / cdn.jsdelivr.net/npm/[email protected]";
const erudaScript = ` <! --erudaArea--> <script src="${erudaCDN}"></script>
<script src="${erudaDomCDN}"></script> <script> eruda.init({ tool: ['console', 'network', 'elements', 'resources', 'snippets', 'sources'], }); eruda.add(erudaDom); </script> <! --endOfRrudaArea-->`;
args[0].eruda = erudaScript;
}
return args;
});
},
configureWebpack: {
/ / configuration HardSourceWebpackPlugin
plugins: [new HardSourceWebpackPlugin()],
},
css: {
loaderOptions: {
// Globally introduce common.scss
sass: {
prependData: '@import "~@/assets/styles/common.scss"; ',},/ / configuration px2vw
postcss: {
plugins: [
new Pxtovw({
unitToConvert: "px".// The unit to convert, default is "px";
viewportWidth: 750.// The viewport width of the design draft
unitPrecision: 5.// The number of decimal places reserved after the unit conversion
propList: ["*"].// List of attributes to be converted,* means match all,! Does not convert
viewportUnit: "vw".// The converted viewport unit
fontViewportUnit: "vw".// The viewport unit used for the converted font
selectorBlackList: [].// CSS selectors without conversion continue to use the original unit
minPixelValue: 1.// Set the minimum conversion value
mediaQuery: false.// Set whether the unit in media query needs to be converted
replace: true.// Whether to replace the attribute value directly without adding the standby attribute
exclude: [/node_modules/].// Ignore files in certain folders}),],},},},},};Copy the code
Effect of validation
OK, let’s compare the effect. Figure 1 shows that HardSource is not enabled, and Figure 2 shows that HardSource is enabled. Of course, since the project is not so big now, the effect is not obvious, but when developing in Webpack-dev-server, there will be a significant speed up in hot loading, which is quite metaphysical.
Babel-plugin-import is introduced on demand
Ts – import – plugins plugin
I personally am not averse to using a mature third-party component library, so FOR this project I introduced Vant. The official TypeScript documentation recommends using TS-import-plugins, but I found that ts-import-plugins were buggy when I used them.
The specific recurrence path is:
- Start by introducing some of the Vant-related components to the page, for example
<Radio>
Such as npm run serve
Run the project and make changes at will<Radio>
Copywriting on the componentCtrl + C
End of run- Once again,
npm run serve
Run the project, then modify it<Radio>
Copywriting on the component - If you look at the page display, you will see that the Vant style is invalid at this point. Non-100% reappearance, you can repeat steps 2 and 3 for testing
- Only delete after invalid
node_modules/.cache/ts-loader
Folder, clearts-loader
The cache can be restored to normal
Babel – plugin – import plug-in
Although this issue only affects the development environment and is packaged normally, it still affects day-to-day development. So instead of using ts-import-plugin, I’ll use tsconfig.json + babel-plugin-import to import on demand.
First let’s change tsconfig.js to compilerOptions:
-
Target: What version of js will be output after compilation, which version will be changed to esNext
-
Module: Specifies the module standard to use, which we also changed to ESNext
-
JSX: Specifies the development environment for which the JSX code is to be used. This is modified to Preserve JSX in preserve mode for subsequent conversion operations (e.g., Babel).
{
"compilerOptions": {
"target": "esnext"."module": "esnext"."jsx": "preserve"."strict": true."importHelpers": true."moduleResolution": "node"."skipLibCheck": true."esModuleInterop": true."allowSyntheticDefaultImports": true."sourceMap": true."baseUrl": "."."types": [
"webpack-env"]."paths": {
"@ / *": [
"src/*"]},"lib": [
"esnext"."dom"."dom.iterable"."scripthost"]},"include": [
"src/**/*.ts"."src/**/*.tsx"."src/**/*.vue"."tests/**/*.ts"."tests/**/*.tsx"]."exclude": [
"node_modules"]}Copy the code
OK, after modifying tsconfig.json, we will install and configure babel-plugin-import.
NPM install -d babel-plugin-import
NPM install -d babel-plugin-import NPM WARN [email protected] requires a peer of postcss@^8.0.0 but none is You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but None is installed. You must install peer dependencies yourself. NPM WARN [email protected] requires A peer of postcss@^8.1.0 but none is installed. You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed. You must install peer Dependencies Yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed Must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but None is installed. You must install peer dependencies yourself. + [email protected] added 1 package from 1 Contributor in 7.169 sCopy the code
After the dependency installation is complete, we add the vant related configuration to babel.config.js
module.exports = {
presets: ["@vue/cli-plugin-babel/preset"].plugins: [["import",
{
libraryName: "vant".libraryDirectory: "es".style: true,},"vant",]]};Copy the code
The idea here is that we first export the compiled code to the ES6+ version via tsconfig.json to support Babel escape, and then configure Babel to import on demand. Many students found that Babel configuration could not be introduced as required after following the official Vant document, because the tsconfig.json file was not configured.
Effect of validation
First we install Vant3.x globally: NPM I vant@next -s
Those who qualify can go onto university. Those who qualify can go onto university. Those who qualify can go onto university vant@next -s NPM WARN [email protected] requires a peer of Postcss @^8.0.0 but none is installed Install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed. You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of Postcss @^8.1.0 but none is installed. You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed. You must install peer Dependencies Yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed Must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but None is installed. You must install peer dependencies yourself. + [email protected] added 6 packages from 2 ficol3in7.807 sCopy the code
Introduce Vant’s Button in SRC /main.ts
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import { Button } from "vant";
createApp(App).use(store).use(router).use(Button).mount("#app");
Copy the code
Look at the size of the package. The CSS file has grown dramatically since the Button contains Vant icon-related styles
Then add more Vant Radio to SRC /main.ts
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import { Button, Radio } from "vant";
createApp(App).use(store).use(router).use(Button).use(Radio).mount("#app");
Copy the code
At this point, you can see that the volume of the package is a little more than when you just packed Button components, proving that the on-demand import is working.
Eslint
Maintaining a consistent code style is especially important in team development. In addition to our daily code conventions, there should be some technical uniformity of style. So we usually use Eslint in our projects. Many people don’t like Eslint because it affects our daily development efficiency. Because Vue Cli4 already installs Eslint packages for us when we initialize them, so here we mainly configure Eslint to format automatically when we save. Allows us to use Eslint to unify the code style without unreasonably affecting our development efficiency.
Install the VSCode plug-in
Where does Eslint and prettier-code formatter fit in VSCode
Configuration. Eslintrc. Js
Since the rules for Lint vary from company to company, I won’t go into detail here. As a simple demonstration, you can set your own Lint rules according to your project’s development specifications
module.exports = {
// Specify configuration file root: indicates that the current file is the root configuration file of ESLint. You do not need to search for the file directory at the next level
root: true.env: { // Run the environment
node: true
},
extends: [ // Inheritance rules
'plugin:vue/vue3-essential'.'plugin:vue/vue3-recommended'.'@vue/standard'.'@vue/typescript/recommended'.'./node_modules/@mlz/lint/ts-eslintrc.js'.// The internal Lint rule library].plugins: [ // Provide plug-ins
'vue'].parserOptions: { // ESLint parses configuration items
parser: '@typescript-eslint/parser'.ecmaVersion: 2020
},
rules: { // Specific rules
'import/no-default-export': 0.'no-unused-expressions': 'off'.'no-return-assign': 'off'.'promise/no-nesting': 'off'.'@typescript-eslint/no-unused-expressions': 2.'@typescript-eslint/no-explicit-any': 'off'.'@typescript-eslint/camelcase': 'off'."@typescript-eslint/interface-name-prefix": 'off'.'vue/singleline-html-element-content-newline': 'off'."@typescript-eslint/no-use-before-define": "off"}}Copy the code
Configuration. Eslintignore
Here I have excluded the dist, bin, config, SRC /typings folders, so you can exclude Lint as you like.
dist/
bin/
config/
vue.config.js
src/typings/
Copy the code
Configuration. Prettirerrc. Js
Prettirerrc because prettirerrc is used here, configure.prettirerrc.js to conform formatting standards to Eslint.
module.exports = {
tabWidth: 2.// A TAB represents several Spaces. The default is 4
useTabs: false.// Whether to use TAB for indentation. The default value is false, indicating that Spaces are used for indentation
singleQuote: true.// Whether to use single quotation marks for strings. The default is false. Use double quotation marks
semi: true.// Whether to use semicolons on line bits. Default is true
trailingComma: "all".Tail / / whether or not to use commas, there are three optional value "< none | es5 | all >"
bracketSpacing: true.{foo: bar} {foo: bar}
parser: "babylon".// The parsing engine for the code, which defaults to Babylon, is the same as Babel.
arrowParens: "always".endOfLine: "lf"
};
Copy the code
The configuration Settings. The json
After the above configuration, let’s configure VSCode’s settings. json so that VSCode can automatically format it according to Eslint rules when we save. Add the following configuration to settings.json:
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true."source.fixAll.tslint": true
},
"eslint.validate": [
"javascript"."typescript"."javascriptreact"."typescriptreact"."html"."vue"].Copy the code
After the configuration is complete, make sure the Eslint icon is displayed in the lower right corner. Try saving the file to see if it is automatically formatted according to Eslint rules. If it doesn’t, restart Vscode.
StyleLint
With Eslint configured, let’s move on to StyleLint.
First we install the StyleLint plug-in for Vscode
Install dependencies
npm i -D stylelint stylelint-scss stylelint-webpack-plugin
Those who qualify NPM I-d stylelint stylelint- SCSS stylelint-webpack-plugin NPM WARN @vue/[email protected] requires a Peer of @typescript-eslint/eslint-plugin@^4.4.0 but none is installed. You must install peer dependencies yourself. NPM WARN @vue/[email protected] requires a peer of @typescript- esLint /parser@^4.4.0 but none is installed. You Must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.0.0 but none is You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but None is installed. You must install peer dependencies yourself. NPM WARN [email protected] requires A peer of postcss@^8.1.0 but none is installed. You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed. You must install peer Dependencies Yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but none is installed Must install peer dependencies yourself. NPM WARN [email protected] requires a peer of postcss@^8.1.0 but You must install peer dependencies yourself. NPM WARN [email protected] requires a peer of Typescript @ ^ 2.2.0 | | ^ 3.0.0 but none is installed. You must install peer dependencies yourself. + [email protected] + [email protected] + [email protected] added 127 packages from 93 ficol3 and updated 1 packagein12.121 sCopy the code
Configuration. Stylelintrc. Json
We already have a set of rules in place, so we won’t go into details here. You can also use a third-party rule library such as stylelint-config-standard
{
//"extends": "stylelint-config-standard", // if there are no custom rules, a third party can be used
"extends": "./node_modules/@mlz/lint/stylelintrc.json".// The company's Stylelint rules
"rules": {
"indentation": 2."unit-case": "lower"}}Copy the code
Configuration. Stylelintignore
# build
/dist/
/build/
# nodemodules
node_modules
Copy the code
Configure the vue. Config. Js
Introduce stylelint-webpack-plugin in vue.config.js and add StyleLintWebpackPlugin in configureWebpack.plugins
// Get the environment configuration
const cfg = require("./config/index") ();const Pxtovw = require("postcss-px-to-viewport");
const HardSourceWebpackPlugin = require("hard-source-webpack-plugin");
const StylelintWebpackPlugin = require("stylelint-webpack-plugin");
module.exports = {
devServer: {
host: cfg.buildtime.origin_server.ip,
port: cfg.buildtime.origin_server.port,
},
chainWebpack: (config) = > {
// HTML template injection configuration
config.plugin("html").tap((args) = > {
// Embed environment configuration script
const configScript = ` <! --configArea--><script>window.CUSTOMCONFIG =The ${JSON.stringify(
config.runtime
)}</script><! --endOfConfigArea-->`;
args[0].config = configScript;
// Inject erUDA in non-local development and production environments
if(! ["local"."production"].includes(cfg.runtime.env)) {
const erudaCDN = "/ / cdn.bootcdn.net/ajax/libs/eruda/2.4.1/eruda.min.js";
const erudaDomCDN = "/ / cdn.jsdelivr.net/npm/[email protected]";
const erudaScript = ` <! --erudaArea--> <script src="${erudaCDN}"></script>
<script src="${erudaDomCDN}"></script> <script> eruda.init({ tool: ['console', 'network', 'elements', 'resources', 'snippets', 'sources'], }); eruda.add(erudaDom); </script> <! --endOfRrudaArea-->`;
args[0].eruda = erudaScript;
}
return args;
});
},
configureWebpack: {
plugins: [
// Configure HardSource to speed up secondary builds
new HardSourceWebpackPlugin(),
/ / configuration styleint
new StylelintWebpackPlugin({
files: ['**/*.{vue,htm,html,css,sss,less,scss}'].fix: true.// Enable automatic recovery
cache: false.// Enable caching
emitErrors: true.failOnError: false,})]},css: {
loaderOptions: {
// Globally introduce common.scss
sass: {
prependData: '@import "~@/assets/styles/common.scss"; ',},/ / configuration px2vw
postcss: {
plugins: [
new Pxtovw({
unitToConvert: "px".// The unit to convert, default is "px";
viewportWidth: 750.// The viewport width of the design draft
unitPrecision: 5.// The number of decimal places reserved after the unit conversion
propList: ["*"].// List of attributes to be converted,* means match all,! Does not convert
viewportUnit: "vw".// The converted viewport unit
fontViewportUnit: "vw".// The viewport unit used for the converted font
selectorBlackList: [].// CSS selectors without conversion continue to use the original unit
minPixelValue: 1.// Set the minimum conversion value
mediaQuery: false.// Set whether the unit in media query needs to be converted
replace: true.// Whether to replace the attribute value directly without adding the standby attribute
exclude: [/node_modules/].// Ignore files in certain folders}),],},},},},};Copy the code
The configuration Settings. The json
After configuration, add source.fixall.stylelint directly to the editor.codeActionsOnSave configuration item in settings.json. This way Vscode will automatically format the StyleLint when we save
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true."source.fixAll.tslint": true."source.fixAll.stylelint": true
},
Copy the code