问题描述
使用webpack配置Vue框架时遇到问题。更准确地说,问题在于单个文件组件中<style>
标记中包含的样式。即使我的配置看起来与许多有关此配置过程的教程完全一样,也不会应用这些样式。在webpack构建过程中没有错误。下面,我提供了一些代码片段,希望其中有人可以发现错误或缺少某些内容。
Webpack配置文件:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
entry: './src/app.js',mode: 'development',output: {
path: path.resolve(__dirname,'dist'),filename: '[name].[contenthash].bundle.js'
},devServer: {
contentBase: path.join(__dirname,port: 8080
},module: {
rules: [
{
test: /\.js$/,exclude: /[\\/]node_modules[\\/]/,loader: 'babel-loader'
},{
test: /\.vue$/,loader: 'vue-loader',},{
test: /\.scss$/,use: [
'vue-style-loader','css-loader','sass-loader'
]
},]
},resolve: {
extensions: ['.js','.vue'],alias: {
'@components': path.resolve(__dirname,'src/components'),}
},plugins: [
new VueLoaderPlugin(),new HtmlWebpackPlugin({
template: './src/assets/index.html',filename: 'index.html'
}),new CleanWebpackPlugin({
cleanStaleWebpackAssets: false
}),],optimization: {
splitChunks: {
chunks: 'all'
}
}
}
Webpack的主条目文件:
import Vue from 'vue';
import TestComponent from '@components/TestComponent';
new Vue({
el: "#app",render: h => h(TestComponent)
});
TestComponent文件:
<template>
<h class="header">from {{ name }}</h>
</template>
<script>
export default {
name: 'TestComponent',data() {
return {
name: 'TestComponent'
}
}
}
</script>
<style lang="scss" scoped>
.header {
color: red;
font-size: 50px;
margin-left: 100px;
}
</style>
index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<Meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
浏览器的最终结果:
解决方法
问题似乎出在默认情况下,css-loader
启用了esModule
导致了问题。我认为它应该在您将其关闭时起作用:
{
loader: 'css-loader',options: {
esModule: false // it's supposed to be turned off
},},