This is the sixth day of my participation in the More text Challenge. For details, see more text Challenge

preface

In the recent vUE source code parsing tutorial video, each chapter explains the use of Webpack, we have to build the scaffolding from scratch, which is too time consuming, this article will describe how to build a WebPack template, which is also convenient for us to use later development or practice. (Pull and play, no need to configure each use).

What is a webpack

Webpack is the most popular module packaging tool in front-end development. It only needs a simple configuration to complete the module loading and packaging.

We can see from the main diagram on the official website that WebPack can bundle multiple files into one or more bundles.

Initialize the project

NPM init -y // initialize git init // initialize git repository TSC --init // generate the tsconfig.json configuration fileCopy the code

Install WebPack and WebPack-CLI (local installation) in the project.

If you use a global install, this will lock webPack in your project to the specified version and may cause the build to fail in projects that use different Versions of WebPack.

npm install webpack webpack-cli --save-dev
Copy the code

Configure the NPM script

Add a “build”: “webpack” to the scripts object in the project’s package.json file. Later we can use NPM run build to get the project running.

"scripts": {
    "build": "webpack"
  },
Copy the code

Project directory structure

We create a SRC under the root directory as the project’s root directory.

Webpack-template ├─ SRC ├─ package.json ├─ tsconfig.json ├─ package.jsonCopy the code

In the pages folder, create the index folder and the HTML, SCSS, and ts files. In the SRC directory, create a main.ts file and write to the main.

// main.ts
console.log('main.ts')
Copy the code
// Introduce index. SCSS in index.ts
import './index.scss'
Copy the code
Webpack-template ├─ SRC │ ├─ pages │ ├─ index │ │ ├─ index.html │ │ ├─ index. Ts │ ├─ main.ts │ ├─ Package-lock.json ├─ package.json ├─ tsconfig.jsonCopy the code

Create the project profile

Create a webpack.config.ts file in the root directory, and WebPack will process the properties defined by the configuration file.

Webpack-template ├─ SRC │ ├─ pages │ ├─ index │ │ ├─ index.html │ │ ├─ index. Ts │ ├─ main.ts │ ├─ Package-locking.json ├─ Package.json ├─ tsconfig.json ├─ webpack.config.tsCopy the code
Writing a Config file
// webpack.config.ts
import * as path from 'path';
import * as webpack from 'webpack';

const config: webpack.Configuration = {
  mode: 'production'.entry: './src/main.ts'.output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'.clean: true,}};export default config;
Copy the code

Execute the installation command in the project to install the required Loader.

npm install --save-dev css-loader style-loader sass-loader sass ts-loader typescript ts-node @types/node @types/webpack html-webpack-plugin
Copy the code

Configure the installed loader and plugins in webpack.config.ts.

Configure the loader

Loader configuration.

 module: {
        rules: [{test: /\.s[ac]ss$/i,
                use: [
                    // Generate the JS string as a style node
                    'style-loader'.// Convert CSS to CommonJS module
                    'css-loader'.// Compile Sass into CSS
                    'sass-loader',]}, {test: /\.css$/i,
                use: ['style-loader'.'css-loader'],}, {test: /\.(png|svg|jpg|jpeg|gif)$/i,
                type: 'asset/resource'}, {test: /\.(woff|woff2|eot|ttf|otf)$/i,
                type: 'asset/resource',},],}Copy the code
Configure plugins

Some related configurations for plugins.

  plugins: [
		new HtmlWebpackPlugin({
            title: 'index'.template: './src/pages/index/index.html'.filename: 'index.html',}),]Copy the code

After installation, run the NPM run script to package the project and get the dist folder, which is the folder containing the files packaged from the SRC folder in our project.

As you can see, there are index. HTML and main.js files inside. Because we are writing ts files, we cannot run directly in the browser.

Configuring multiple Pages

Why configure multiple pages here?

Now Vue, React, Angular these three frameworks are SPA, start directly NPM run serve

However, in many scenarios, SPA development mode may not be applicable, for example, sometimes our school holds activity pages, or usually write some simple pages, in fact, this time more pages are more appropriate.

Because most of the time these pages are completely unrelated, there is no need to share data between them, and you can even use A different technology stack for each individual page. For example, page A uses Vue, page B uses React, and page C uses Angular.

Next, we will configure our Webpack-Template for multiple pages.

Create a new hello folder in the SRC/Pages folder of your project, and put the HTML, SCSS, and TS files in the same folder as index. This is the second page.

SRC ├─ pages │ ├─ hello │ ├─ hello.html │ ├─ hello.ts │ ├─ index │ ├─ index.html │ ├─ index └ ─ index. Ts └ ─ main. TsCopy the code
// hello.html
...
<body>
    <h2>
        hello.html
    </h2>
</body>.Copy the code
// hello.ts
import './hello.scss'
console.log('hello.ts');
Copy the code

In the webpack.config.ts configuration file, change the entry and output properties to:

Entry: {main: '. / SRC/main. Ts', 'index' : '. / SRC/pages/index/index. Ts', / / the index page 'hello'... '. / SRC/pages/hello/hello.html ts', / / hello page}, the output: {path: the path. The resolve (__dirname, 'dist), filename: 'js/[name]/[name].js', clean: true, }Copy the code

Because the contents of multiple pages are different, you need to configure multiple HTMLWebPackPlugins on an array of plugins.

attribute instructions
title Page title, i.edocument.title
filename Name of the file to be exported
template Page template, pointing topagesNext to the corresponding pagehtmlfile
chunks The injected script file (be sure to configure this!! Otherwise, all script files will be injected into the current page.

For more information on how to configure the HtmlWebpackPlugin plugin, please read: github.com/jantimon/ht…

 plugins: [
        new HtmlWebpackPlugin({
            title: 'index'.filename: 'index.html'.template: './src/pages/index/index.html'.chunks: ['index'.'main']}),new HtmlWebpackPlugin({
            title: 'hello'.filename: 'hello.html'.template: './src/pages/hello/hello.html'.chunks: ['hello'.'main']})],Copy the code

Now let’s run the NPM run build command again to package our project.

Open hello. HTML and hello. HTML, and our corresponding page files in the Pages folder are processed by the HtmlWebpackPlugin into the corresponding HTML file.

Configuration Code specification

Students with basic engineering literacy will pay attention to Code specifications, and Code Linting (or Lint for short) is an important way to ensure the consistency of Code specifications.

EditorConfig

EditorConfig is used to configure the formatting code. The formatting code must match ESlint’s configuration, otherwise the formatted code will not conform to ESlint’s rules and the project will not be packaged properly.

Add a.editorConfig file to the project root directory. The.editorConfig file defines formatting rules.

# Editor configuration, see http://editorconfig.org# indicates the top-level EditorConfig configuration file root =true[*] # indicates that charset = UTF applies to all files- 8 -Set the file character set to UTF- 8 -Indent_style = space # indented style (TAB | space) indent_size =2# # end_of_line indentation size = lf control line type (lf | cr | CRLF) trim_trailing_whitespace =true# Remove any whitespace at the beginning of a line insert_final_newline =true# Always insert a new line at the end of the file [*.md] # indicates that the following rule applies only to MD files max_line_length = off TRIM_trailing_whitespace =false
Copy the code

Tip: If you are using the VS Code editor, you need to install the EditorConfig for VS Code plugin in the plugin marketplace.

ESlint

ESlint is an open source code inspection tool that looks for problematic patterns or code that doesn’t depend on specific coding styles. For most programming languages there is code checking, and generally the compiler has a built-in checking tool.

In team development, there are different coding styles and habits among team members. ESlint can be used to solve this problem. When a code style does not conform to ESlint rules, it will prompt the code rules and automatically fix them. Keep your project’s coding style consistent.

Install ESlint

npm install eslint-webpack-plugin eslint --save-dev
Copy the code

Configuration ESlint

Open the terminal in the project root directory, run NPM eslint –init, and complete a series of Settings as prompted by the terminal to generate the configuration file

What problems would you like to detect using ESlint?

Here we choose the syntax, find the problem, and enforce the coding specification

Ask what type of modules your project uses

Does your project use the following framework?

We choose none here

Does your project use typescript?

Let’s say YES

What environment is your code running on?

We’re going to choose browser here

Which code style do you define your project in this way?

We choose the mainstream style here

Which style do you want to follow?

We’re going Airbnb style here

Select the format of the ESLint configuration file

The JS file is chosen as its configuration file format

Do you want to install them using NPM now?

We select YES here, and they will start installing these dependencies for us

At this point, the.eslintrc.js configuration file is automatically generated in the project root directory:

module.exports = {
  env: {
    browser: true.es2021: true,},extends: [
    'airbnb-base',].parser: '@typescript-eslint/parser'.parserOptions: {
    ecmaVersion: 12.sourceType: 'module',},plugins: [
    '@typescript-eslint',].rules: {}};Copy the code

Configure the ESlint plugin in webpack.config.ts and add ESLintPlugin to the plugins property

import ESLintPlugin from 'eslint-webpack-plugin';
// plugins
new ESLintPlugin({
      extensions: ['js'.'ts'].exclude: '/node_modules/',}).Copy the code

Tip: if you are using the vscode editor, you need to install the ESLint plugin in the plugin marketplace and enable the ESLint service.

To test whether the configuration is successful, declare a variable in a TS file without adding a semicolon. The editor will prompt you with a red wavy line.

Open the settings.json configuration file in the vsCode editor and add the following code:

 "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
 }
Copy the code

When configuring ESlint, there are a lot of red wavy lines popping up, and clicking on them is slow. What’s a quick way to fix this problem?

Sure!!!!!

Eslint provides the –fix option to Automatically fix problems, so we’ll add a quick script to package.json to Automatically fix files with extensions js and ts in the SRC folder, with the –ext option, Is the directory specified for repair.

"lint": "eslint --fix --ext .js,.ts src"
Copy the code

Execute NPM run Lint to fix all problems in the current project.

husky

Husky is a Git Hook tool. It implements pre-commit esLint checksum and commit validation. Our project already has code specification checks, but at some point, one or two specification warnings may be missed, or even ignored! Close the detection tool and write the code according to its original coding specification. To solve this problem, we need to restrict the commit of “problematic” code to ensure that all the code in the GIT repository is ESlint compliant. Husky is where we need to go.

Run the husky-init command to quickly initialize a Husky configuration on the project.

npx husky-init && npm install
Copy the code

When it’s done, it’s configured, right. It’s as simple as that.

Husky \pre-commit and replace the NPM test command with eslint –fix — ext.js,.ts SRC.

Eslint –fix — ext.js,.ts SRC; esLint –fix — ext.js,.ts SRC;

lint-staged

Lint-lean is a tool that runs linters on git staged files. When we run the command esLint or stylelint, it only checks the files we added to the staged with git Add. This can prevent us from having to check the entire project code every time we check.

Install the lint – staged

npm i lint-staged -D
Copy the code

Add the Lint-Passage configuration item to package.json.

"lint-staged": {
    "*.{js,ts}": "eslint --fix"
  },
Copy the code

Eslint –fix only on.js,.ts files in git staging

Modified.husky/pre-commit to replace eslint –fix — ext.js,.ts SRC commands with NPX Lint-staged

npx lint-staged
Copy the code

The last

Webpack-template is an example of how to build a front-end development project template from an empty folder. Webpack-template is an example of how to build a front-end development project template from an empty folder. The purpose is also convenient when we use the WebPack environment at ordinary times, reduce the tedious configuration to save time.

Webpack-template GIT: github.com/QC2168/webp…

Later may also configure some technology stack, pay attention to I don’t get lost oh! 😉 😉

Code word is not easy, click 👍