webpack5.27+vue2.6.12版本处理css文件以及.vue文件的<style>css模块

一. 问题背景

笔者最近在学习如何用webpack+vue搭建工程,当前webpack的版本为5.27.0,发现一些webpack3、4的写法已经不适用了,特此将正确方法记录下

A. 过时写法

用如下命令加载依赖

cnpm install --save vue
cnpm install --save-dev vue-loader
cnpm install --save-dev vue-style-loader
cnpm install --save-dev vue-template-compiler

webpack中配置如下:

var path = require('path');

//用插件
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var config = {
    entry: {
        main: './vue'
    },
    output: {
    	publicPath: '/dist/',
        path: path.join(__dirname, './dist'),
        filename: 'main.js'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
                // 
				options: {
                    loaders: {
                        css: ExtractTextPlugin.extract({
                          use: 'css-loader',
                          fallback: 'vue-style-loader'
                        })
                    }
                }
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            }
        ]
    }
    ,plugins: [
        // 重命名提取后的css文件
		new ExtractTextPlugin("main.css")
    ]
};

module.exports = config;

vue.js文件如下:

import Vue from 'vue';
// 导入app.vue组件
import App from './app.vue';

// 创建Vue 根实例
new Vue({
    el: '#app',
    render: h => h(App)
});

app.vue中用到了模板:

<template>
    <div>Hello {{ name }}</div>
</template>
<script>
    export default {
        data () {
            return {
                name: 'Vue.js'
            }
        }
    }
</script>
<style scoped>
    div{
        color: #f60;
        font-size: 24px;
    }
</style>
B. 报错提示

其他babel配置入标准,启动程序后,报如下错误:

ERROR in ./app.vue?vue&type=style&index=0&id=381730fa&scoped=true&lang=css&14:3
Module parse failed: Unexpected token (14:3)
File was processed with these loaders: * ./node_modules/vue-loader/lib/index.js You may need an additional loader to handle the result of these loaders. | |

div{ | color: #f60; | font-size: 24px; @ ./app.vue 4:0-87 @ ./vue.js 7:11-31

ERROR in ./app.vue?vue&type=template&id=381730fa&scoped=true& 2:0
Module parse failed: Unexpected token (2:0) File was processed with these loaders: * ./node_modules/vue-loader/lib/index.js You may need an additional loader to handle the result of these loaders. |

Hello {{ name }}
| @ ./app.vue 1:0-94 11:2-8 12:2-17 @ ./vue.js 7:11-31

ERROR in ./app.vue Module Error (from ./node_modules/vue-loader/lib/index.js): vue-loader was used without the corresponding plugin. Make sure to include VueLoaderPlugin in your webpack config. @ ./vue.js 7:11-31

1 error has detailed information that is not shown. Use ‘stats.errorDetails: true’ resp. ‘–stats-error-details’ to show it.

webpack 5.27.1 compiled with 3 errors in 4519 ms i 「wdm」: Failed to compile.

也就是说app.vue文件没有的得到正确解析,vue-loader以及css、template处理都失败了。网上搜了搜处理方法,但大多都是过时,终于最终调试成功,特此记录

二. 解决办法

A. 不要用ExtractTextPlugin插件,改用MiniCssExtractPlugin

可参考:MiniCssExtractPlugin

B. 不在test: /\.vue$/中加loaders,而是另用rule:test: /\.css$/来处理css文件和style标签;并用插件VueLoaderPlugin处理vue结果
1. 若想webpack编译提取出独立的.css文件,通过在<head>标签中<link type='text/css'>引用此.css,则可以不用MiniCssExtractPlugin插件,而是直接用vue-style-loader去解析
var path = require('path');

//用插件
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');

var config = {

    output: {
    	publicPath: '/dist/',
        path: path.join(__dirname, './dist'),
        filename: 'main.js'
    },    
    
    entry: {
        main: './vue'
    },
    // 提取独立的.css文件
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            // 它会应用到普通的 `.css` 文件以及 `.vue` 文件中的 `<style>` 块
            {
                test: /\.css$/,
                use: [
               		//用MiniCssExtractPlugin处理结果
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            }
        ]
    }
    ,plugins: [
        // 引入VueLoader插件
        new VueLoaderPlugin(),

        // // 重命名提取后的css文件
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: "[id].css"
        })
    ]
};

module.exports = config;

最后的引用效果如下,编译出/dist/main.css的独立文件,index.html是用过link引用的
在这里插入图片描述

在这里插入图片描述

2. 若不想webpack编译提取独立的css文件,而是想通过在<head>标签中<style>使用css,则可以不用MiniCssExtractPlugin插件,而是直接用vue-style-loader去解析

写法如下:

var path = require('path');

//用新插件
const VueLoaderPlugin = require('vue-loader/lib/plugin');

var config = {
    entry: {
        main: './vue'
    },
    output: {
    	publicPath: '/dist/',
        path: path.join(__dirname, './dist'),
        filename: 'main.js'
    },
    module: {
        rules: [
             // Vue.js用法
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            // 此rule会应用到普通的 `.css` 文件以及 `.vue` 文件中的 `<style>` 块
            {
                test: /\.css$/,
                use: [
                    'vue-style-loader',
                    'css-loader'
                ]
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            }
        ]
    }

    ,plugins: [
        // 引入VueLoader插件
        new VueLoaderPlugin()
    ]
};

module.exports = config;

但以上用法使得css以<style type=“text/css”>方式引入
在这里插入图片描述

总结

Vue和webpack随时间发展更新迭代很快,很多技术方法随时间而变化或者失效,要做好项目最好指定自己熟悉的相应版本,或者及时学习最新的搭建方式

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Webpack 是一个现代 JavaScript 应用程序的静态模块打包工具,可以将多个模块打包成一个或多个静态资源文件Vue 是一个流行的 JavaScript 框架,用于构建用户界面。 在将 Vue 项目打包时,可以使用 Webpack 来生成公共的配置文件,以便在不同的环境中共享和重复使用。 首先,可以创建一个名为 `webpack.base.config.js` 的公共配置文件。该文件会包含一些通用的配置,例如入口文件、输出路径、加载器、插件等。通常,会将所有环境共有的配置项放在这个文件中。例如: ```javascript module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, // 其他加载器规则... ], }, plugins: [ new VueLoaderPlugin(), // 其他插件... ], }; ``` 然后,在不同的环境配置文件(如 `webpack.dev.config.js`、`webpack.prod.config.js` 等)中,可以通过引入公共配置文件并进行合并来继承公共的配置。例如: ```javascript const merge = require('webpack-merge'); const baseConfig = require('./webpack.base.config.js'); module.exports = merge(baseConfig, { // 为开发环境或生产环境添加额外的配置项 }); ``` 这样,可以在不同的环境中共享公共配置,减少重复工作,并且方便管理和维护项目。 最后,可以使用命令行或配置文件来指定要使用的环境配置文件,以便在打包时根据不同的环境生成不同的配置。 通过使用 Webpack 生成公共配置文件,可以更好地组织和管理 Vue 项目的打包配置,提高开发效率,并且方便进行项目的扩展和维护。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郭Albert

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值