可以javascript与webpack内联吗?

Leo*_*eon 16 webpack

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

例如:

库代码:

(function(){
   var a = 0;
})();
Run Code Online (Sandbox Code Playgroud)

我需要在html中内联这段代码.

HTML:

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

  <body>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我可以用webpack实现这个吗?我找到了脚本加载器,但它运行脚本,而不是内联.

Dus*_*son 21

我已经开始使用html webpack插件来支持这个.您指定正则表达式以匹配要嵌入内联的文件.

plugins: [
  new HtmlWebpackPlugin({
        inlineSource: '.(js|css)$' // embed all javascript and css inline
    }),
  new HtmlWebpackInlineSourcePlugin()
] 
Run Code Online (Sandbox Code Playgroud)


Ita*_*zki 8

在内联源的帮助下,我没有喝了一口气:

  1. 安装inline-source-cli: npm install inline-source-cli
  2. inline属性添加到html文件中的脚本标记:<script inline src="path/to/index.js"></script>
  3. inline-source --root ./dist dist/path/to/index-pre.html > dist/path/to/index.html


Leo*_*eon 6

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

HTML:

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

  <body>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

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/'));
    });
Run Code Online (Sandbox Code Playgroud)

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

"build": "rimraf dist && webpack --progress --hide-modules --config build/webpack.prod.conf.js;gulp replace-and-inline"
Run Code Online (Sandbox Code Playgroud)

如果要发布项目,只需运行即可 npm run build


2018年7月20日更新

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

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