【问题标题】:how to get content of file which are using require when auto importing node_moduels package?自动导入node_modules包时如何获取使用require的文件内容?
【发布时间】:2017-12-21 06:13:49
【问题描述】:

我正在使用 angular 1.6 和 gulp 以及 live reload 和 babel 来运行开发服务器。使用 yarn 安装所有 Angular 包,因此使用 npmfiles 自动导入 index.html 中的依赖项。

所有包都添加到最终 index.html 中的适当位置,但该文件仅包含 node_modules/package/package.json "main: attributes

中提到的相应 index.js 的内容

例如。添加角度库。 final .tmp/index.html 有以下内容

<script src="/../node_modules/angular/index.js"></script>

但是这个angular/index.js有以下内容

 require('./angular');
 module.exports = angular;

但我想要 Angular js 文件的内容

此外,它会在控制台中为每个包提供多个错误

未捕获的 ReferenceError: 要求未在 index.js:1 中定义

这里是相关代码

gulp.task('connectDev', function() {
    connect.serverClose();
    connect.server({
        name: 'Zeus:Dev',
        root: [path.join(conf.paths.tmp, '/serve'), conf.paths.src],
        port: 3000,
        debug: false,
        host: '127.0.0.1',
        fallback: path.resolve('./.tmp/serve/index.html'),
        livereload: true,
        directoryListing: false,
        middleware: function(connect) {
            return [connect().use('/node_modules', connect.static('node_modules'))];
        }
    });
});

并使用此任务添加所有 node_modules 库

 var npmVendors = gulp.src(mainNPMFiles( {nodeModulesPath: '../node_modules/'} ));
  // .pipe($.babel({"presets": ["env"]}));

  var npmOptions = {
    relative: true,
    starttag: '<!-- inject:ang:{{ext}} -->',
    ignorePath: [conf.paths.src, path.join(conf.paths.tmp, '/serve')],
    addRootSlash: true,
    // transform: function (filePath, file) {
    //     return file.contents.toString('utf8');
    // }
  };

在 src/index.html 中

<!-- inject:ang:js -->
<!-- endinject -->

现在,如果我取消注释 transform 属性,它会直接在 index.html 中添加文件的内容,而无需 &lt;sctipt&gt; 标记

所以我的问题是如何添加文件的原始内容而不是 index.js 的 2 行

【问题讨论】:

    标签: angularjs gulp-inject gulp-livereload


    【解决方案1】:

    浏览器不理解 require 语句。您将不得不使用依赖捆绑工具,例如 browserify 或带有 gulp 的 webpack。

    在 gulp 中再添加一项任务来浏览您的依赖项,它会自动捕获您的完整源代码和供应商代码

    gulp 可以使用 browserify 插件。

    更新

    我为你创建了一个sample project。请试一试

    【讨论】:

    • 你能帮我如何添加,在哪里添加?我不想使用 webpack
    • 在哪里插入浏览器?在 npmOption 或 npmVendors 内? here是相关gulp任务的完整文件
    • @pro.mean 你可以使用 Bower 包管理器吗?使用 bower 安装 angular 不会产生此类问题,您可以轻松地将 bower 文件加载到 index.html。
    • 我想离开凉亭,这就是我以这种方式更改代码的主要原因。鲍尔放弃了它的支持。否则,bower 可以正常使用wiredep
    • 我也是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2015-08-25
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    相关资源
    最近更新 更多