gpt4 book ai didi

javascript - 在 webpack.config.js 中使用 Promise 的结果

转载 作者:行者123 更新时间:2023-12-02 23:18:43 24 4
gpt4 key购买 nike

我正在尝试访问在 webpack.config.js 中的 recursive.js 创建的 Promise(文件路径数组)(遍历我的目录并对样式表进行排序) 这样我就可以按特定顺序编译所有样式表。

似乎webpack.config.js无法访问recursive.js的结果,并且它没有生成我的.css/.scss文件包!

我实际上想不出解决这个问题的方法...我认为在 .then( result => { 内有 module.exports = { ... } ... } ) 就足够了...但我相信 module.exports 尝试在结果准备好之前使用它,并且它只生成 main.js

recursive.js

const readdirp = require('readdirp');

let files = readdirp.promise('src/lib/bs4',
{
entryType: 'files', fileFilter: ['*.css', '*.scss'], directoryFilter: ['!modulos', '!node_modules', '!assets']
})
.then(function (files) {
return new Promise((resolve, reject) => {
resolve(promises = files.map(files => files.path))
})
}).then(function (result) {
let cssArr = []
let scssArr = []
result.forEach(e => {
let temp = e.split('.')
if (temp[temp.length - 1] === 'css') {
cssArr.push(e)
//cssArr.push(e.replace(/\\/g, '/'))
} else {
scssArr.push(e)
//scssArr.push(e.replace(/\\/g, '/'))
}
})
console.log(cssArr.concat(scssArr))
return cssArr.concat(scssArr)
})

exports.files = files

webpack.config.js

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ext = require('./recursive')


ext.files.then((result) => {
return new Promise((resolve, reject) => {
resolve(promises = result.map(e => e = path.resolve(__dirname, `src/lib/bs4/${e}`)))
// .map(e => e.replace(/\\/g, '/')))
})
})
.then((result) => {
console.log(result) // prints out the expected array of file paths!

module.exports = {
entry: {
bundle: result,
main: [
path.resolve(__dirname, 'src/principal')
]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css"
}),
]
};

})

我相信我不应该在 .then((result) => { } 内的 webpack.config.js 文件中使用 module.exports )

还有其他方法可以解决这个问题吗?

谢谢大家!

更新

我阅读了更多内容来尝试理解 FZ 和 Steve Holgado(非常感谢!)试图解释的内容,并且我修改了我的代码,使其行为如下:

const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const readdirp = require('readdirp');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

// extracts argument (path) from script command
const args = require('minimist')(process.argv.slice(2));

// development or production?
const devMode = process.env.NODE_ENV !== "production";

const configPromise = readdirp.promise('src/lib/bs4',
{
// if a file (stylesheets/images) is not being imported/required its extension needs to be added to the fileFilter: []
// e.g.: removing '*.png' won't bundle images from 'src\lib\bs4\imgs'
entryType: 'files', fileFilter: ['*.css', '*.scss', '*.png'], directoryFilter: ['!modulos', '!node_modules', '!assets']
})
.then(function (files) {
return files = files.map(file => file.path);
})
.then(function (result) {
return new Promise((resolve, reject) => {
let cssArr = [];
let scssArr = [];
result.forEach(element => {
let temp = element.split('.');

(temp[temp.length - 1] === 'css') ? cssArr.push(element) : scssArr.push(element)

})

// .scss files first then .css
result = scssArr.concat(cssArr);
result = result.map(element => path.resolve(__dirname, `src/lib/bs4/${element}`));

// Path to the first file in the queue (src/..)
if (!args['path']) {
console.log(' ******* Path to main stylesheet NOT added ******* ');
} else {
console.log(' ******* Path to main stylesheet ADDED ******* ');
result.unshift(path.resolve(__dirname, args['path']));
}

// console.log(args['path'])
// console.log(result)

resolve({
mode: devMode ? 'development' : 'production',
entry: {
// main: './src/principal.js',
// bundle.css
bundle: result,
},
output: {
// filename: 'principal.js',
path: path.resolve(__dirname, 'bundle-css'),
},
optimization: {
minimizer: devMode ? [] : [
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.css$/,
})
]
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader, // 3. Extract css into files
'css-loader', // 2. Turns css into commonjs
'sass-loader' // 1. Turns sass into css
]
},
{
test: /.(svg|png|jpe?g|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/',
}
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
exclude: /images/, // avoid having copies of .svg fonts into 'images/'
}
}
]
}
],
},
plugins: [
new MiniCssExtractPlugin({
filename: devMode ? '[name].[hash].css' : '[name].[hash].min.css'
}),
new CleanWebpackPlugin({
cleanAfterEveryBuildPatterns: ['bundle-css'] // clean output.path directory
})
]
})
})
})

module.exports = configPromise

以下是我用来运行它的命令,以防有人也需要帮助:

  "scripts": {
"bundle-css-dev": "cross-env NODE_ENV=development webpack --config ./bundle-css.config.js --progress --colors",
"bundle-css-prod": "cross-env NODE_ENV=production webpack --config ./bundle-css.config.js --progress --colors"
},

要运行其中一个脚本:npm run bundle-css-dev -- --path="path_to_first_file_in_queue"

最佳答案

您可以从 webpack.config.js 导出函数并返回 promise 。

Webpack 将等待 promise 解决:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ext = require('./recursive')

module.exports = () => {
return ext.files
.then((result) => {
return new Promise((resolve, reject) => {
resolve(promises = result.map(e => e = path.resolve(__dirname, `src/lib/bs4/${e}`)))
// .map(e => e.replace(/\\/g, '/')))
})
})
.then((result) => {
console.log(result) // prints out the expected array of file paths!

return {
entry: {
bundle: result,
main: [
path.resolve(__dirname, 'src/principal')
]
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css"
}),
]
}
})
}

关于javascript - 在 webpack.config.js 中使用 Promise 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57046658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com