携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第10天,点击查看活动详情
基于之前的文章 基于webpack,不使用任何脚手架,创建纯粹的webpack项添加css文件,如下:
require('./static/index.css');
const init=require('./components/index.js')
init('问问计算机:webpack是怎么回事?');
调用npm run build编译提示如下错误信息:
ERROR in ./main.js 1:0-29
Module not found: Error: Can't resolve 'style-loader' in 'D:******'
resolve 'style-loader' in 'D:******'
Parsed request is a module
using description file: D:******\package.json (relative path: .)
resolve as module
在webpack.config.js中添加style-loader 如下:
const path=require('path');
module.exports={
entry:'./main.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname,'../dist')
},
module:{
rules:[
{
test:/.css$/,
use:['style-loader']
}
]
}
}
调用npm run build编译提示如下错误信息:
ERROR in ./main.js 1:0-29
Module not found: Error: Can't resolve 'style-loader' in ...
安装style-loader
npm install style-loader
调用npm run build编译提示如下错误信息:
ERROR in ./static/index.css 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, ...
webpack.config.js修改如下:
const path=require('path');
module.exports={
entry:'./main.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname,'../dist')
},
module:{
rules:[
{
test:/.css$/,
use:['style-loader','css-loader'] //添加css-loader
}
]
}
}
运行index.html效果如下:
当前的项目结构依赖关系如下:
这些现象的背后发生了什么?像之前一样,配置vscode的调试环境,如下 launch.json:
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "askcomputer-webpack",
"type": "node-terminal",
"request": "launch",
"command": "npm run build",
"skipFiles": [],
"cwd": "${workspaceFolder}"
},
]
}
package.json 如下:
{
"name": "askcomputer-webpack-s-loader",
"version": "1.0.0",
"description": "webpack原理",
"main": "main.js",
"scripts": {
"build": "webpack --progress --config ./config/webpack.config.js",
"dev": "webpack-dev-server --progress --config ./config/webpack.dev.conf.js"
},
"author": "askcomputer",
"license": "ISC",
"dependencies": {
"css-loader": "^6.7.1",
"style-loader": "^3.3.1",
"webpack": "^5.74.0"
},
"devDependencies": {
"webpack-cli": "^4.10.0"
}
}
通过这种方式一是避免在调试环境上浪费时间,另外就是明确基于本篇文章的依赖版本同步,避免因为版本不同产生歧义。
然后在node_modules下的webpack/lib/Compiler.js/Compiler下添加断点,如下:
接着就是在vscode的调试窗口中点击启动按钮,便可以命中断点,并且出现调用堆栈,能够明确看到的这一流程的堆栈调用的过程,这种方法基本上在所有语言的ide中都适用,如下:
以上就是对于查看webpack编译原理所要准备的基础环境。它的重要程度对于相对高级别需求的程序员来说可能是不可或缺的技能,因为当市场上已有的Loader和Plugin不能满足要求的时候,就需要基于原理的前提条件下自定义Loader和Plugin,否则会有一种无从下手的无力感。
下一篇文章详细解析Compiler.js中的方方面面。