欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

入门级前端工程实践构建:HTML与JS的加载流程详细解析

最编程 2024-02-20 10:00:56
...

学习来源:掘进小课---初探前端工程化

搭建普通项目

创建项目文件夹

我的项目命名为webpack-project

初始化项目

执行命令npm init
执行完该命令后,紧接着就会有交互提示,这是需要输入项目的一些配置,可以在这个时候认真填写,或者回车跳过先创建好,后面再去修改。

package name: (0-1webpack) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository:
keywords: 
author: 
license: (ISC) 
About to write to /Users/workspace/self/0-1webpack/package.json: 
{ 
    "name": "0-1webpack", 
    "version": "1.0.0", 
    "description": "", 
    "main": "index.js", 
    "scripts": { 
        "test": "echo "Error: no test specified" && exit 1" 
    },
    "author": "", 
    "license": "ISC" 
}
Is this OK? (yes)

Is this OK之后,项目中便会创建package.json配置文件,处理使用npm init,也可手动创建该配置文件,并添加配置项。
3.创建了配置文件之后,便是要进入前端页面所需的三大件,HTML,Javascript,CSS。    创建index.html文件和src文件夹,在src文件夹下创建index.js和index.css文件。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="./src/index.css" />
  </head>
  <body>
    <div id="app" />
    <script src="./src/index.js"></script>
  </body>
</html>
// index.js
const app = document.querySelector("#app");
app.innerHTML = "Hello World";
// index.css
#app {
  color: red;
}

以上代码,运行html文件,可以在浏览器中看到红色字体的hello world,此时,表明一个简单的项目搭建完成了。
此时,打开浏览器的控制台,会发现html文件,js文件和css文件的加载,那么这里就会暴露一个问题:如果项目存在多个html文件,多个js文件,多个css文件,浏览器依旧会加载出这些文件,也就是会发起网络请求,那么出现的结果就是存在一个非常非常长的请求列表,此时,需要一个打包工具---前端常用的打包工具,即webpack

使用webpack管理

安装webpack

使用webpack进行打包以及包管理之前,肯定是要先下载安装webpack依赖的。执行命令npm install webpack(参考webpack官网
下载安装完成之后,那么就需要根据官网文档介绍,来进行webpack的配置了。

webpack配置

1.创建webpack.config.js文件,这个文件就是webpack的相关配置内容
首先要做的就是配置入口文件和输出文件

// webpack.config.js
module.exports = {
  entry: {
    index: "./src/main.js"
  },
  output: {
    filename: "bundle.js"
  }
};

2.然后就是创建main.js文件作为项目的入口文件

import "./a.js";
import "./index.js";

3.那么,此时在index.html文件中,对于js方法的引入也需要相应的修改

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="./src/index.css" />
  </head>
  <body>
    <div id="app" />
    <div id="app2" />
    <script src="src/main.js" type="module"></script>
  </body>
</html>

4.接下来就是运行打包命令啦:执行命令webpack:
然而,事情并不美好,我运行的时候报错了:

webpack: The term 'webpack' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

此时,需要度娘:webpack可能没有找到,回想一下,我的webpack安装并不是全局的,那么,可能就需要进行环境变量的配置了。类似下面这样的操作:

image.png

image.png 当然,除此之外,也有其他办法:

  • 全局安装 webpack :npm install webpack -g 。
  • 执行命令换成 ./node_modules/.bin/webpack 。
  • 在 npm scripts 中添加指令:"build": "webpack" 。
  • npx webpack。

然而,以上问题解决之后,再次执行打包命令,依旧没有成功,为什么呢?因为没有安装webpack-cli插件,此时,终端其实是会提示的,输入yes就自动下载啦。

image.png 安装完成之后,再次运行打包命令(我没有安装全局,而是在npm script中添加了build命令,然后运行了npx webpack命令),此时打包成功,并且多了一个dist文件(webpack没有专门在配置中声明的话,默认打包文件放在dist文件夹下),里面也有了bundle.js文件,此时,我们再次运行html看看。
哦豁~完蛋,出现了报错:

image.png 根据错误信息大概可以看出来原因在于使用了 File 协议,应该使用提示的“http, data, chrome, chrome-extension, chrome-untrusted, https”这些协议。要解决这个问题,我们可以使用 DevServer 创建一个支持 http 的本地服务
但是,不要慌,webpack也有解决办法:webpack提供了 webpack-dev-server ,支持快速开发应用程序。

// 下载依赖
npm install webpack-dev-server --save-dev

// webpack.config.js 增加配置
module.exports = { 
  entry: {
    index: "./src/main.js"
  },
  output: {
    filename: "bundle.js"
  },
  static: {
    directory: "./"
  },
  port: 8080
}

// package.json的script中增加命令
"scripts": {
    "test": "npm run test",
    "build": "webpack",
    "dev": "webpack-dev-server"
},
// 然后就是执行npm run dev命令(这个命令大家都很熟悉吧)

but,事情并没有那么简单,我又出现了一下问题,把我整的是一脸懵逼,这是个啥呀?

Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
// 配置对象是无效的。[webpack](https://so.****.net/so/search?q=webpack&spm=1001.2101.3001.7020)在初始化过程中,使用的配置对象与API模式中的不匹配。
 - configuration has an unknown property 'port'. These properties are valid:
   object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry?, experiments?, externals?, externalsPresets?, externalsType?, ignoreWarnings?, infrastructureLogging?, loader?, mode?, module?, name?, node?, optimization?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, snapshot?, stats?, target?, watch?, watchOptions? }
   -> Options object as provided by the user.
   For typos: please correct them.
   For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.
     Loaders should be updated to allow passing options via loader options in module.rules.
     Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
     plugins: [
       new webpack.LoaderOptionsPlugin({
         // test: /\.xxx$/, // may apply this only for some modules
         options: {
           port: …
         }
       })
     ]

此时,我看到了下面的plugins的写法,于是,我抄下来了。再次运行,又一次出现了webpack is not defined。真是一波三折:

[webpack-cli] Failed to load 'D:\study\webpack-project\webpack.config.js' config
[webpack-cli] ReferenceError: webpack is not defined
    at Object.<anonymous> (D:\study\webpack-project\webpack.config.js:13:9)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:101:18)
    at WebpackCLI.tryRequireThenImport (D:\study\webpack-project\node_modules\webpack-cli\lib\webpack-cli.js:204:22)
    at loadConfigByPath (D:\study\webpack-project\node_modules\webpack-cli\lib\webpack-cli.js:1404:38)
    at WebpackCLI.loadConfig (D:\study\webpack-project\node_modules\webpack-cli\lib\webpack-cli.js:1510:44)

度娘告诉我,这是因为我没有引入webpack,我怎么犯了这个低级的错误o(╥﹏╥)o

const webpack = require("webpack");

but,最开始的问题并没有得到真正的解决(配置对象是无效的。webpack在初始化过程中,使用的配置对象与API模式中的不匹配。)
查,查官网,发现plugins的写法不一样了,再一看,我的webpack下载的是@5.xx版本的,好吧。
根据官网实例,重新写配置

// webpack.config.js
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
  mode: "development",
  entry: {
    index: "./src/main.js"
  },
  output: {
    filename: "bundle.js"
  },
  plugins: [
    new webpack.LoaderOptionsPlugin({
      // test: /\.xxx$/, // may apply this only for some modules
    }),
    new HtmlWebpackPlugin({ template: "./public/index.html" })
  ],
  devServer: {
    compress: true,
    port: 9000
  }
};

ps:后面才发现,先前的报错,是因为static写的位置不对,捂脸哭泣~
此时,编译成功了,但是,控制台请求中main.js报404了,难过。

未完待续。。。