[英]Using the result of a Promise in webpack.config.js
I'm trying to access a Promise (an array of file paths) created in recursive.js (goes through my directories and sorts my stylesheets) in my webpack.config.js so I can compile all my stylesheets in a specific order. 我试图在webpack.config.js中访问在recursive.js中创建的Promise(文件路径数组)(浏览目录并排序样式表),以便可以按特定顺序编译所有样式表。
It seems that webpack.config.js is not able to access the result from recursive.js and it is not generating my bundle of .css/.scss files! 看来webpack.config.js无法从recursive.js访问结果,并且没有生成我的.css / .scss文件包!
I actually can't think of a way to solve this...I thought that having the module.exports = { ... } inside .then( result => { ... } ) would be enough...but it I believe that module.exports tries to use result before it's even ready and it only generates main.js 我实际上想不出解决办法...我认为在.then (result => {...})里面放入module.exports = {...}就足够了...但是我相信module.exports尝试在结果尚未准备好就使用它,并且只会生成main.js
recursive.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 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"
}),
]
};
})
I believe I shouldn't be using module.exports in my webpack.config.js file inside .then((result) => { } ) . 我相信我不应该在.then ((result)=> {})内的webpack.config.js文件中使用module.exports 。
Are there another ways around this? 还有其他解决方法吗?
Thanks, guys! 多谢你们!
UPDATE 更新
I read bit more to try and understand what FZs and Steve Holgado (Thanks a lot!) were trying to explain, and I modified my code to behave like this: 我阅读了更多内容,以尝试了解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
Here are the commands I'm using to run it in case someone needs help with that too: 如果有人也需要帮助,这是我用来运行它的命令:
"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"
},
To run one of the scripts: npm run bundle-css-dev -- --path="path_to_first_file_in_queue" 要运行以下脚本之一:npm run bundle-css-dev---path =“ path_to_first_file_in_queue”
You can export a function from webpack.config.js and return a promise. 您可以从webpack.config.js导出函数并返回承诺。
Webpack will wait for the promise to resolve: Webpack将等待诺言解决:
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"
}),
]
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.