WebPack编译TS文件而不包含在HTML中



我正在开发一个简单的网页,试图根据用户操作选择性地加载脚本。

因此,我希望WebPack编译一个脚本,但不要自动添加为输出HTML中的导入(脚本标记(。我的设置(见下文(在index.html 中创建了一个main.js和一个具有以下输出的optional.js

<script src="main.js"></script><script src="optional.js"></script>

是否有一些配置可以更改,以便输出html中不包含optional.js


以下是的相关文件

// tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: {
main: './src/index.ts',
optional: './src/optional.ts'
},
module: {
rules: [
{
test: /.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader'
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
}
}
]
},
{
test: /.(woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
}
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
minify: {
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
minifyCSS: true,
minifyJS: true
},
cache: false
}),
new MiniCssExtractPlugin({
filename: 'css/style.css'
}),
new CompressionPlugin({
test: /.(js|css)$/,
algorithm: 'gzip',
}),
]
}

您可以使用inject: false:禁用自动注入

// ...
new HtmlWebpackPlugin({
inject: false,
template: './src/index.html',
// ...

通过这种方式,您必须手动添加脚本(index.html(:

<script src="main.js"></script>

使用模板引擎(例如ejs(的机会是使用htmlWebpackPlugin.files.js:访问编译的文件

// index.html
<% for(var js in htmlWebpackPlugin.files.js) { %>
<% if (js === 'main.js') { %>
<script src="<%= js%>"></script>
<% } %>
<% } %>

最新更新