【发布时间】:2021-08-10 19:29:42
【问题描述】:
我正在使用 create-react-app 创建一个使用 Storybook JS 的组件库。目的是发布一个 NPM 包,这些组件可以在其他项目中使用。该库使用 SASS,定义了全局变量并将其导入src/index.js 文件。
我正在测试我的 NPM 包,并尝试将它与 Webpack V4 捆绑在一起。在另一个本地项目上使用npm link 已经半成功。但是,我遇到了 MiniCssExtractPlugin 的问题,其中样式根本没有插入到该项目的 HEAD 中。
SASS 样式表被转换为 CSS 并添加到我的组件库项目的 dist/ 文件夹中,没有任何问题。但是当通过 NPM 包将组件导入到我的其他项目时,这些不会在任何地方应用,例如import { Button } from '@my-account/components';
使用样式加载器时,我的开发环境没有问题,样式直接插入到带有<style>标签的DOM中。我确定我一定遗漏了一些东西,但我觉得我已经用尽了一切来尝试诊断这个。 create-react-app 与此插件不兼容吗?还是没有通过 NPM 包自动将样式注入到项目的 HEAD 中?
如果我将文件从 NPM 包导入到本地项目中,则样式确实有效,例如import '@my-account/components/dist/main.cd2be00655e79c5077cb.css'; - 但如果样式定期更新并且文件在其名称中使用哈希,这似乎无法维护?
我尝试添加 HtmlWebpackPlugin 来创建 index.html 文件,但这并没有解决问题。
任何帮助将不胜感激!
webpack.config.prod.js
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'production',
devtool: 'source-map',
entry: './src/index.js',
output: {
path: path.resolve('dist'),
filename: 'index.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules)/,
use: 'babel-loader',
}
],
rules: [
{
test: /\.scss$/,
sideEffects: true,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-resources-loader',
options: {
resources: require(path.join(process.cwd(), 'src/assets/sass/WebpackStyles.js')),
hoistUseStatements: true
}
}
],
},
]
},
resolve: {
extensions: ['.js'],
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: '[name].[hash].css'
})
]
};
【问题讨论】:
标签: javascript reactjs npm webpack create-react-app