导入较少是未定义的



src/pages/login/index.tsx中,导入的styles未定义。但src/pages/login/index.less确实存在。

index.tsx:

import React from 'react';
import styles from './index.less';
const Login: React.FC = () => {
console.log(styles); // undefined
return <div className={styles.login}>Login Page</div>

无指数:

.login {
position: relative;
width: 200px;
height: 100px;
background: red;
}

有人能告诉我怎么解决吗?


我使用webpack作为构建工具,这是我的webpack配置:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const autoprefixer = require('autoprefixer');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const rootDir = process.cwd();
function resolve(dir) {
return path.join(__dirname, '.', dir);
}
module.exports = {
entry: path.resolve(rootDir, 'src/index.tsx'),
output: {
path: path.resolve(rootDir, 'dist'),
filename: 'bundle.[contenthash:8].js',
clean: true
},
module: {
rules: [
{
test: /.(jsx|js)$/,
use: 'babel-loader',
include: path.resolve(rootDir, 'src'),
exclude: /node_modules/
},
{
test: /.css$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: false
}
}
]
},
{
test: /.less$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: false
}
},
'postcss-loader',
{
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true
}
}
}
]
},
{
test: /.s[ac]ss$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: false
}
},
'sass-loader'
]
},
{
test: /.(png|jpg|gif|jpeg|webp|svg|eot|ttf|woff|woff2)$/,
type: 'asset'
},
{
test: /.(ts|tsx)$/, 
use: [
{
loader: 'thread-loader',
options: {}
},
'babel-loader',
{
loader: 'ts-loader',
options: {
happyPackMode: true,
transpileOnly: true
}
}
]
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
alias: {
'@': resolve('src')
}
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(rootDir, 'public/index.html'),
inject: 'body',
scriptLoading: 'blocking'
}),
new MiniCssExtractPlugin({
filename: 'css/[name].css'
}),
new CopyWebpackPlugin({
patterns: [
{
from: '*.js',
context: path.resolve(rootDir, 'public/js'),
to: path.resolve(rootDir, 'dist/js')
}
]
}),
new MiniCssExtractPlugin({
filename: 'css/[name].css'
}),
new webpack.optimize.SplitChunksPlugin()
],
optimization: {
splitChunks: {
chunks: 'all' 
},
minimizer: [new CssMinimizerPlugin()]
}
};

modules: false设置为modules: true以获得更小的值。

{
test: /.less$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true
}
},
'postcss-loader',
{
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true
}
}
}
]
},

最新更新