将单独的脚本注入HTML

时间:2018-08-20 14:04:40

标签: javascript html webpack

说我有一个public/index.html文件

,然后是一个名为otherScript的单独的html文件,它只是一个包含<script>标签和脚本的文件

如何将这些脚本注入到我的public/index.html文件中?

我要使用new HtmlWebpackPlugin

但是在示例中它只是说:

new HtmlWebpackPlugin({
  template: 'public/index.html'
  inject: true
})

我看不到应该链接到other html文件的任何地方吗?

3 个答案:

答案 0 :(得分:2)

如果它是HTML文件,则可以使用名为raw-loader的Webpack加载器加载它,也可以使用html-loader

并像这样使用它:

Webpack.config

{
  test: /\.html$/,
  use: 'raw-loader'
}

模块

// import file

import htmlFile from 'myfile.html';

// insert the contents of file at end of body

var body = document.getElementsByTagName('body')[0];
body.insertAdjacentHTML('beforeEnd', htmlFile);

但是,一个充满脚本标签的HTML文件听起来像是不当行为的IMO。

如果要将脚本插入页面,我建议完全使用其他方法。

一种方法是使用importrequire正常导入脚本,或者您可以有一系列依赖项来像这样加载和加载它们:

var dependencies = [
    'path/to/script/1.js',
    'path/to/script/2.js'
]

for(var i = 0; i < dependencies.length; i++) {
    let script = document.createElement('script');
     script.type = 'text/javascript';
     script.src = dependencies[i];
     document.getElementsByTagName('head')[0].appendChild(script);
}

答案 1 :(得分:0)

无法使用webpack做到这一点,特别是使用html-webpack-plugin。该属性“注入”将由webpack创建的所有脚本注入到您在“模板”属性中获得的html中。

答案 2 :(得分:0)

您可以使用html-webpack-tags-plugin插件。

如果要在脚本上启用缓存清除,这将很有帮助,这是我不想仅使用(Session info: headless chrome=80.0.3987.122) Process finished with exit code 1 和静态脚本元素的主要原因。

webpack.dev.config.js

copy-webpack-plugin

webpack.prod.config.js

new HtmlWebpackTagsPlugin({
  // this script must be loaded before all other scripts
  append: false,
  tags: ['src/myScript.js'],
}),
相关问题