javascript可以与webpack内联吗? [英] can javascript be inline with webpack?

查看:55
本文介绍了javascript可以与webpack内联吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个库导入到我的项目中,该库应该是一个javascript文件,需要内联到html中.

I need to import a library to my project, the library should is a javascript file, which need to be inlined to html.

例如:

库代码:

(function(){
   var a = 0;
})();

我需要用html内联此代码.

I need to make this code inline in html.

html:

<html>
  <head>
    <script>
      (function(){
         var a = 0;
      })();
    </script>
  </head>

  <body>
  </body>
</html>

我可以用webpack来实现吗?我发现脚本加载器,但是它运行脚本,而不是内联.

can I implement this with webpack? I find script-loader, but it run the script, not make it inline.

推荐答案

最后,我们通过组合webpack和gulp解决了这个问题.(有两个插件:gulp-html-replace和gulp-inline-source.)

At last, we solve this problem by combining webpack and gulp. (with two plugins: gulp-html-replace and gulp-inline-source.)

html:

 <html>
  <head>
    <!-- build:js -->
    <!-- endbuild -->
  </head>

  <body>
  </body>
</html>

gulpfile:

  gulp.task('replace-and-inline', function () {
      return gulp.src('./dist/index.html')
        .pipe(htmlreplace({
          'js': {
            src: [your libs which you want to be inline],
            tpl: '<script src="%s" inline></script>'
          }
        }))
        .pipe(inlinesource())
        .pipe(gulp.dest('./dist/'));
    });

在package.json中,定义一个任务,该任务将使用webpack编译项目,然后将js文件作为内联注入.

In package.json, define a task, which will compile the project using webpack and then inject the js file as inline.

"build": "rimraf dist && webpack --progress --hide-modules --config build/webpack.prod.conf.js;gulp replace-and-inline"

要发布项目时,只需运行 npm run build

When you want to release your project, just run npm run build

2018年7月20日更新

update on July.20 2018

我们制作了一个webpack插件来解决此问题.

we have made a webpack plugin to solve this issue.

https://github.com/QuellingBlade/html-webpack-inline-plugin

这篇关于javascript可以与webpack内联吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆