【问题标题】:recreating gulp config on webpack在 webpack 上重新创建 gulp 配置
【发布时间】:2018-09-24 11:26:36
【问题描述】:

现在真的需要帮助来理解 webpack,虽然我尝试了这么多,但我仍然不明白如何将 webpack 用作任务运行器,而不仅仅是模块捆绑器。这是一个学习的过程,所以请不要讨论为什么 gulp/webpack 比其他的更适合这种工作。

您看到代码实际上非常简单,其想法是基于模板抓取每个 html 文件,该模板注入了来自 css 和 js 的同名变量。这个 gulpfile 是我用来创建 Polymerjs Html 文件的文件。

有什么方法可以将其转换为特定于 Webpack 的构建工具?我应该把爬取webpack中文件夹的信息放在哪里?我应该把它放到 index.js 中吗?

我理解为Webpack使用特定入口文件的概念,但是面对这种用例,我该怎么办?

gulp.task('templates', function() {
// crawl folder pathToFolder
    readdir(pathToFolder, ['*.scss', '*.js', '*.json'], function(err, files) {
        // loop every file founds
        files.forEach(function(file) {
            let data = file.substr(10);
            // make sure the path is correct when used on windows device.
            data = data.replace(String.fromCharCode(92), String.fromCharCode(47));
            let index = data.lastIndexOf('/');
            let path = data.substr(0, index);
            let scss = file.substr(0, file.lastIndexOf('.')) + '.scss';
            let js = file.substr(0, file.lastIndexOf('.')) + '.js';
            let json = file.substr(0, file.lastIndexOf('.')) + '.json';
            // process all files into their respective loader and squash it into one variable to use on the template.
            let process = {
                css: '',
                form: '',
                js: '',
                json: '',
            };
            if (fs.existsSync(scss)) {
                process = Object.assign(process, {
                    css: sass.compiler.renderSync({
                        file: scss,
                    }).css,
                });
            }
            if (fs.existsSync(js)) {
                process = Object.assign(process, {
                    js: fs.readFileSync(js, 'utf8'),
                });
            }
            if (fs.existsSync(json)) {
                let x = gulp.src('./ramen-renderer.html')
                    .pipe(template({
                        json: json,
                    }));
                process = Object.assign(process, {
                    json: x,
                });
                // jsonProcess = Object.assign(jsonProcess, {json: fs.readFileSync(json, "utf8")});
            }
            // render the final html path with gulp-template
            return gulp.src(file)
                .pipe(template(process))
                .pipe(gulp.dest('src/' + path));
        });
    });
});

【问题讨论】:

  • 使用 path 模块代替这些字符串替换来进行与操作系统无关的路径操作。

标签: javascript webpack gulp


【解决方案1】:

webpack 不是一个任务运行器,而是一个模块打包器。这意味着您需要另一种方式来运行任务。最常见的方法是为此使用 NPM。您在脚本部分下的 package.json 中定义您的任务。

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 2013-11-08
    • 2012-11-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 2016-11-28
    • 2018-06-03
    相关资源
    最近更新 更多