Webpack 將檔案(.css、.js)收集到一個庫中,并在另一個 React 專案中使用它。組件中指定的樣式不會通過,盡管 .css 檔案存在并且樣式在那里。
UiButton.jsx 檔案
import styles from './UiButton.module.css';
const UiButton = () => {
return (
<>
<button className={styles.button}>Text</button>
</>
);
}
export default UiButton;
index.js 檔案
import UiButton from './UiButton/UiButton';
import './index.css';
export { UiButton };
Webpack.config.js 檔案
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: { main: './src/index.js' },
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
libraryTarget: "umd",
library: "uilibrarytest"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [ 'style-loader', MiniCssExtractPlugin.loader, 'css-loader' ]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'index.css',
}),
// new HtmlWebpackPlugin({
// template: './public/index.html',
// }),
new webpack.ProvidePlugin({
"React": "react",
}),
],
resolve: {
extensions: ['.js', '.jsx'],
},
}
這是 webpack 構建的:
.button {
background: red;
}
html {
margin: 0;
padding: 0;
}
如何使它在使用給定庫中的組件時,樣式也被拉到它?
uj5u.com熱心網友回復:
Webpack 中的加載器是從右到左評估的。在您的配置中,評估順序是“css-loader”、MiniCssExtractPlugin.loader,最后是“style-loader”。但是 'style-loader' 只將樣式注入到 DOM 中。您需要 MiniCssExtractPlugin.loader 成為“use”陣列中的第一個元素。見下文...
{
test: /\.css$/,
use: [ MiniCssExtractPlugin.loader, 'css-loader' ]
}
此外,您可以告訴 webpack 在生產期間使用 MiniCssExtractPlugin.loader ,而在其他時候使用 'style-loader'。
const isProduction = process.env.NODE_ENV == 'production';
const stylesHandler = isProduction ? MiniCssExtractPlugin.loader : 'style-loader';
...other config
{
test: /\.css$/,
use: [ stylesHandler, 'css-loader' ]
}
在你的 package.json 腳本中,
"build": "webpack --mode=production --node-env=production"
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/337325.html
標籤:javascript css 反应 网络包
