• 从零开始学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.comvueday1html4.从0开始学VUEsimpleloader>npm run build
    
    > simpleconfig@1.0.0 build D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    > 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.comvueday1html4.从0开始学VUEsimpleloadersrccssstyle.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:Usersext.zhangyugen1AppDataRoaming
    pm-cache\_logs2021-06-03T06_28_16_970Z-debug.log
    
    D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader>

    可以看到报错了,报错提示中是处理到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.comvueday1html4.从0开始学VUEsimpleloader>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_modulesfsevents):
    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_moduleswatchpack-chokidar2
    ode_modulesfsevents):
    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.comvueday1html4.从0开始学VUEsimpleloader>

    安装成功后查看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.comvueday1html4.从0开始学VUEsimpleloader>npm run build
    
    > simpleconfig@1.0.0 build D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    > webpack
    
    (node:20176) UnhandledPromiseRejectionWarning: TypeError: this.getResolve is not a function
        at Object.loader (D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    ode_modulescss-loaderdistindex.js:62:27)
        at LOADER_EXECUTION (D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    ode_modulesloader-runnerlibLoaderRunner.js:119:14)
        at runSyncOrAsync (D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    ode_modulesloader-runnerlibLoaderRunner.js:120:4)
        at iterateNormalLoaders (D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    ode_modulesloader-runnerlibLoaderRunner.js:232:2)
        at Array.<anonymous> (D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    ode_modulesloader-runnerlibLoaderRunner.js:205:4)
        at Storage.finished (D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    ode_modulesenhanced-resolvelibCachedInputFileSystem.js:40:15)
        at D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    ode_modulesenhanced-resolvelibCachedInputFileSystem.js:77:9
        at D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    ode_modulesgraceful-fsgraceful-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.comvueday1html4.从0开始学VUEsimpleloader>

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

    修改为3.6.0尝试一下

    重新执行

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

    再次执行打包

    D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader>npm run build
    
    > simpleconfig@1.0.0 build D:zhangyugen@jd.comvueday1html4.从0开始学VUEsimpleloader
    > 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.comvueday1html4.从0开始学VUEsimpleloader>

    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.comvueday1html4.从0开始学VUEsimpleloader>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_modulesfsevents):
    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_moduleswatchpack-chokidar2
    ode_modulesfsevents):
    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.comvueday1html4.从0开始学VUEsimpleloader>

    查看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' ]
                }
            ]
        }
    }

    再次执行打包

    打包成功~

    运行效果

    颜色已经改变了,开心~

    作者:彼岸舞

    时间:202167

    内容关于:VUE

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

  • 相关阅读:
    便携版Mysql安装
    Markdown 语法学习
    布局页中的特殊情况(比如说只有某页有的banner)
    Jsp Layout 布局页
    eclipse变量名自动补全
    java中的final关键字(2013-10-11-163 写的日志迁移
    java的重载(overload) (2013-10-11-163 写的日志迁移
    java 的多态(2013-10-11-163 写的日志迁移
    java中类与对象的概念(2013-05-04-bd 写的日志迁移
    java的一些相关介绍(2013-10-07-163 写的日志迁移
  • 原文地址:https://www.cnblogs.com/flower-dance/p/14857959.html
Copyright © 2020-2023  润新知