从零开始学VUE之Webpack(使用CSSLoader和StyleLoader转化样式文件)

拷贝一份项目重新命名为simpleloader(拷贝过程会慢,应为其中存在module依赖)

在这个目录结构中,我将main.js从JS文件夹中提取了出来,放到了src目录下,应为一般关于主文件一般都是和文件夹同一级的,比如index.html,其他的就是改了一下webpack.config.js中的源码打包位置

这时我们有一个新的需求,就是需要新增css文件,一般开发中不可能只要JS文件的

在src下新建css文件夹,并新增style.css

style.css

body{
    background-color: yellowgreen;
}

webpack在打包时只会将相互依赖关联主js的文件打包,并不会将无关文件打包,所以我们需要在main.js文件中导入style.css

// 导入css
require('./css/style.css');

运行npm run build

D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader>npm run build

> simpleconfig@1.0.0 build D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader
> webpack

Hash: d6f024f72928ac471688
Version: webpack 3.6.0
Time: 37ms
    Asset     Size  Chunks             Chunk Names
bundle.js  3.07 kB       0  [emitted]  main
   [0] ./src/main.js 111 bytes {0} [built]
   [1] ./src/js/test.js 85 bytes {0} [built]
   [2] ./src/css/style.css 275 bytes {0} [built] [failed] [1 error]

ERROR in ./src/css/style.css
Module parse failed: D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader\src\css\style.css Unexpected token (1:4)
You may need an appropriate loader to handle this file type.
| body{
|     background-color: yellowgreen;
| }
 @ ./src/main.js 5:0-26
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! simpleconfig@1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the simpleconfig@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ext.zhangyugen1\AppData\Roaming\npm-cache\_logs\2021-06-03T06_28_16_970Z-debug.log

D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader>

可以看到报错了,报错提示中是处理到style.css的时候报错了,提示你需要一个属性loader来处理这种类型的文件(You may need an appropriate loader to handle this file type.)

安装配置CSSloader

访问webpack官网

官网:https://webpack.js.org/

中文网:https://www.webpackjs.com/

 

 

然后就可以安装官网的使用说明开始安装配置了

安装css-loader

执行 npm install --save-dev css-loader

D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader>npm install --save-dev css-loader
npm WARN css-loader@5.2.6 requires a peer of webpack@^4.27.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN simpleconfig@1.0.0 No description
npm WARN simpleconfig@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ css-loader@5.2.6
added 26 packages from 60 contributors and audited 394 packages in 17.431s

10 packages are looking for funding
  run `npm fund` for details

found 2 low severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details

D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader>

安装成功后查看package.json

可以看到多了css-loader版本为5.2.6

在webpack.config.js中添加 module:{xxx}

// 需要从node依赖中引入 需要添加依赖环境
const path = require('path');

module.exports = {
    // 配置源码打包位置
    entry: './src/main.js',
    // 配置目标位置
    output: {
        // path 只能写绝对路径 不能写相对路径 但是不要直接写死,需要动态获取文件位置
        path: path.resolve(__dirname,'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                // use: [ 'style-loader', 'css-loader' ] 因为没有安装 style-loader 所以先删除掉style-loader
                use: ['css-loader' ]
            }
        ]
    }
}

再次执行打包

在执行的时候报错了

D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader>npm run build

> simpleconfig@1.0.0 build D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader
> webpack

(node:20176) UnhandledPromiseRejectionWarning: TypeError: this.getResolve is not a function
    at Object.loader (D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader\node_modules\css-loader\dist\index.js:62:27)
    at LOADER_EXECUTION (D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader\node_modules\loader-runner\lib\LoaderRunner.js:119:14)
    at runSyncOrAsync (D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader\node_modules\loader-runner\lib\LoaderRunner.js:120:4)
    at iterateNormalLoaders (D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader\node_modules\loader-runner\lib\LoaderRunner.js:232:2)
    at Array.<anonymous> (D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader\node_modules\loader-runner\lib\LoaderRunner.js:205:4)
    at Storage.finished (D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:40:15)
    at D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:77:9
    at D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader\node_modules\graceful-fs\graceful-fs.js:123:16
    at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:20176) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:20176) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader>

在网上百度了一番,说是css-loader版本太高了,现在我的版本是5.2.6

修改为3.6.0尝试一下

重新执行

npm install --save-dev css-loader@3.6.0

再次执行打包

D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader>npm run build

> simpleconfig@1.0.0 build D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader
> webpack

Hash: e29c484ddbe1ca26b75f
Version: webpack 3.6.0
Time: 240ms
    Asset     Size  Chunks             Chunk Names
bundle.js  5.66 kB       0  [emitted]  main
   [0] ./src/main.js 111 bytes {0} [built]
   [1] ./src/js/test.js 85 bytes {0} [built]
   [2] ./src/css/style.css 283 bytes {0} [built]
    + 1 hidden module

D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader>

ok成功了,就是应为版本的问题

运行效果

通过打包可以看到,打包是没有问题的style.css也打包成功了,但是页面并没有渲染CSS,这显然是存在问题的

就是在刚才配置webpack.config.js的时候我们删除掉了style-loader,会不会是应为这个原因呢,经过百度后发现css-loader只负责打包,并不负责解析渲染,style-loader才负责解析渲染,再次去官网找style-loader

安装配置StyleLoader

明确说明将模块的导出作为样式添加到DOM中

点击一下查看使用

执行安装style-loader

npm install style-loader --save-dev
D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader>npm install style-loader --save-dev
npm WARN css-loader@3.6.0 requires a peer of webpack@^4.0.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN style-loader@2.0.0 requires a peer of webpack@^4.0.0 || ^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN simpleconfig@1.0.0 No description
npm WARN simpleconfig@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ style-loader@2.0.0
added 8 packages from 7 contributors and audited 406 packages in 7.531s

12 packages are looking for funding
  run `npm fund` for details

found 10 vulnerabilities (2 low, 8 moderate)
  run `npm audit fix` to fix them, or `npm audit` for details

D:\zhangyugen@jd.com\vue\day1\html\4.从0开始学VUE\simpleloader>

查看package.json

已经添加了style-loader 版本为2.0.0

配置webpack.config.js

将刚才注释掉的style-loader解开

// 需要从node依赖中引入 需要添加依赖环境
const path = require('path');

module.exports = {
    // 配置源码打包位置
    entry: './src/main.js',
    // 配置目标位置
    output: {
        // path 只能写绝对路径 不能写相对路径 但是不要直接写死,需要动态获取文件位置
        path: path.resolve(__dirname,'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
              // 这个loader在加载的时候webpack是从右向左加载的,顺序写错了,也可能会报错
                use: [ 'style-loader', 'css-loader' ]
            }
        ]
    }
}

再次执行打包

打包成功~

运行效果

颜色已经改变了,开心~

作者:彼岸舞

时间:2021\06\07

内容关于:VUE

本文属于作者原创,未经允许,禁止转发

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值