This is the 7th day of my participation in Gwen Challenge

start

  • The NPM init initialization project is executed

  • Create a new SRC folder to store the project code

  • Create a build folder to store the packaged output files of the project

  • Type in index1.js

    import person from './person.json'
    
    console.log(person)
    
    function add(x, y) {
    	return x + y
    }
    console.log(add(2.3))
    Copy the code
  • Webpack. / SRC /index -o./build/build.js –mode=development

  • Package./ SRC /index.js output into./build/index.js

  • To simplify things, you can write this command to the package.json configuration file and give it an alias

  • Add: “build”: “webpack. / SRC /index.js -o./build/build.js –mode=development” to the script property

You can then execute NPM run build instead to achieve the same effect

Package information includes file size, time, and hash value

Packaging CSS

  • Create webpack.config.js, the webpack configuration file

    const path = require('path')
    module.exports = {
    	entry: './src/index.js'.// Import file
    	output: { // Output file
    		filename: 'build.js'.// The output file name
    		path: path.resolve(__dirname, 'build') // The path to the output file
    	},
    	module: { // The dependent module
    		rules: [{
    				test: /\.css$/.// Matches a file with the suffix CSS
    				use: [// Write in the correct order
    					'style-loader'.// Insert the js style string into the HTML page as a head tag
    					'css-loader'.// Change the styles in the CSS file to js strings]},]},plugins: [].mode: 'development',}Copy the code
  • Creating a CSS File

    // Write a simple stylehtml.body {
    	margin: 0;
    
    }
    
    body {
    	background-color: aqua;
    }
    Copy the code
  • Import ‘./index.css’ from the entry file index.js to introduce index.css

  • After repackaging, you can see that index.css has been introduced in build.js

  • Open the index.html file and see the imported styles inside

Packaging HTML

  • Download the html-webpack-plugin

  • Const HtmlWebpackPlugin = require(‘html-webpack-plugin’)

  • Add configuration in webpakc.config.js

    	plugins: [
    		new HtmlWebpackPlugin({
    			title: 'Output Management'// Title title of the HTML file
    			template: './src/index.html',// Customize the template file})].Copy the code

May be an Error: Error: always find module ‘webpack/lib/node/NodeTemplatePlugin’

NPM install webpack –save-dev re-install webpack in current project (global install may not find)

Packaging pictures

file-loader

  • Download file-loader NPM install file-loader -d

  • Add configuration to Module

    {
        test: /\.(jpg|jpg|gif)$/,// Matches files with these suffixes
        use: [{
            loader: 'file-loader',
            options: {// File loader configuration option}}}]Copy the code

url-loader

Url-loader is similar to file-loader except that it can limit file size

  • Download NPM install url-loader -d

  • Add configuration to Module

        rules: [
          {
            test: /\.(png|jpg|gif)$/,
            use: [
              {
                loader: 'url-loader'.options: {
                  limit: 8192// If the file size is less than 8192 bytes, it is imported as base64, otherwise it is imported normally (path form)}}]}]Copy the code

devServer

Files can be automatically packaged when they are changed, avoiding repeated packaging and improving development efficiency

  • Download the plugin NPM install webpack-dev-server -d

  • Add a devServer property to save the configuration

    DevServer: {contentBase: path.resolve(__dirname, 'build'), True,// Whether the browser automatically opens}Copy the code

Extracting CSS files

  • The style-loader dependency is to insert CSS into the HEAD tag of an HTML file, imported internally

  • NPM install mini-css-extract-plugin-d

  • Add the configuration to the plugins property

    //const MiniCssExtractPlugin = require('mini-css-extract-plugin'
    new MiniCssExtractPlugin({
        filename: 'css/build.css'
    })
    		
    Copy the code
  • Change the CSS loading mode in the module

    {
        test: /\.css$/,
        use: [
        // 'style-loader',// generate a style tag and place it in the style
        MiniCssExtractPlugin.loader,// Link label is imported externally
        'css-loader',
        ]
    }
    Copy the code

CSS compression

  • NPM install optimize- CSS-assets -webpack-plugin -d

  • Configure in plugins

    / / const OptimizeCssAssetsWebpackPlugin = the require (' optimize - CSS - assets - webpack - plugin ') / / introduction in advance
    new OptimizeCssAssetsWebpackPlugin()
    Copy the code

Js syntax check

  • NPM install eslint eslint-loader -d the eslint-loader used depends on ESlint

  • Using the Airbnb specification, download an eslin-config-Airbnb-base package, NPM instal eslint-config-base eslint-plugin-import -d instal eslint-config-base eslint-plugin-import -d

  • Add verification rules to module

    {
        test: /\.js$/.// Matches the js file
        exclude: /node_modules/.// Exclude the contents of the node_modules folder without validation
        loader: 'eslint-loader'./ / rely on
        options: {}/ / configuration items
    }
    Copy the code
  • Add an additional property —-**eslintConfig ** to package.json

    "EslintConfig ":{"extends":"airbnb-base"}Copy the code
  • Package files to see a bunch of errors, and then follow the prompts to change the errors a little bit

Js compatibility processing

babel-loader

  • Download NPM install babel-loader @babel/preset-env -d

  • Configure rules in module

    {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
            presets: [
            '@babel/preset-env'
            ]
        }
    }
    Copy the code
  • Add ES6 syntax to js files

  • After packaging, you can see the packaged file with a syntax change from const to var

@babel/ Polyfill all compatible

  • downloadnpm install @babel/polyfill - D
  • Directly at the top of the JS file import '@babel/polyfill'
  • The packed file is too large

Core.js is compatible with loading on demand

  • Download NPM install core.js -d

  • Add configuration to Module

    {
        test: /\.js$/,// Matches the js file
        exclude: /node_modules/,// Exclude files in node_modules
        loader: 'babel-loader',/ / rely on
        options: {/ / configuration items
            presets: [
                [
                    '@babel/preset-env',
                    {
                        useBuiltIns: 'usage',// Load as needed
                        corejs: {
                            version: 3/ / core. Js version
                        },
                        targets: {
                            chrome: '60',// Compatible with Chrome to version 60
                            firefox: '60',
                            ie: '9',
                            safari: '10',
                            edge: '17',}}]]}},Copy the code

Pay attention to the point

  • Babel-loader is only compatible with simple syntax, but not with complex syntax such as Promise
  • @babel/ Polyfill is simple to use but too big to pack
  • It is recommended to use core.js to load compatibility on demand

Clear the last packed file

  • Download the plugin npm install clen-webpack-plugin -D
  • The introduction of the pluginconst {CleanWebpackPlugin} = require('clean-webpack-plugin')
  • Plugin configuration in webpack.config.js
	new CleanWebpackPlugin()
Copy the code

Matches the precedence of the suffix name

resolve:{
	extensions: ['.js'.'.vue'.'.json'].// "extensions"
}
Copy the code

Complete configuration file

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
module.exports = {
	entry: './src/index.js'.output: {
		filename: 'js/build.js'.path: path.resolve(__dirname, 'build')},module: {
		rules: [{
				test: /\.css$/,
				use: [
					MiniCssExtractPlugin.loader,
					'css-loader',]}, {test: /\.(jpg|png|gif)$/,
				loader: 'file-loader',},/ / {
			// test: /\.js$/,
			// exclude: /node_modules/,
			// loader: 'babel-loader',
			// options: {
			// presets: [
			/ / /
			// '@babel/preset-env',
			/ / {
			// useBuiltIns: 'usage',
			// corejs: {
			// version: 3
			/ /},
			// targets: {
			// chrome: '60',
			// firefox: '60',
			// ie: '9',
			// safari: '10',
			// edge: '17',
			/ /}
			/ /}
			/ /]
			/ /]
			/ /}
			// },
			/ / {
			// test: /\.js$/,
			// exclude: /node_modules/,
			// loader: 'eslint-loader',
			// options: {}
			// }]},plugins: [
		new HtmlWebpackPlugin({
			template: './src/index.html'.minify: {collapseWhitespace:true.removeComments:true,}}),new MiniCssExtractPlugin({
			filename: 'css/index.css',}).new OptimizeCssAssetsWebpackPlugin({

		})
	],
	mode: "production".devServer: {
		hot:true.port: 3000.open: true.compress: true.// Whether to compress files
		contentBase: path.resolve(__dirname, 'build')}}Copy the code