HtmlWebpackPlugin将bundle.[hash].js/css加载到基础twig文件中。

huangapple go评论66阅读模式
英文:

HtmlWebpackPlugin load bundle.[hash].js/css into base twig file

问题

Here's the translated content from your provided text:

我在webpack.config.js中有两个条目,一个用于JS,一个用于SCSS。我可以在开发模式和生产模式下运行。如果我创建一个生产构建,我会得到以下文件:index.html、main[hash].js、main[hash].css。在index.html中,我有链接和脚本标签,它们的src属性指向这些文件。我如何在部署应用程序时加载这些链接和脚本标签到我的base.twig文件中?
在开发模式下,它会从base.twig中加载main.js,并且在该文件中包含了所有内容。

base.twig

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

文件结构:

HtmlWebpackPlugin将bundle.[hash].js/css加载到基础twig文件中。

index.html

<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
    <link href="main.7a67bd4eae959f87c9bc.css" rel="stylesheet">
  </head>
  <body>
    <script type="text/javascript" src="main.7a67bd4eae959f87c9bc.js"></script>
  </body>
</html>

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');

module.exports = (env, options) => {
    const devMode = options.mode === 'development';

    return {
        mode: (devMode) ? 'development' : 'production',
        watch: devMode,
        devtool: "source-map",
        entry: [
            './resources/javascript/index.js',
            './resources/sass/app.scss'
        ],
        output: {
            path: path.resolve(__dirname, 'public/assets'),
            filename: devMode ? '[name].js' : '[name].[hash].js'
        },

        module: {
            rules: [
                {
                    test: /\.twig/,
                    loader: 'twig-loader'
                },
                {
                    test: /\.js$/,
                    exclude: /(node_modules)/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env']
                        }
                    }
                },
                {
                    test: /\.(sa|sc|c)ss$/,
                    use: [
                        {
                            loader: devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
                        },
                        {
                            loader: "css-loader",
                        },
                        {
                            loader: "postcss-loader"
                        },
                        {
                            loader: "sass-loader",
                            options: {
                                implementation: require("sass")
                            }
                        }
                    ]
                },
                {
                    test: /\.(png|jpe?g|gif|svg)$/,
                    use: [
                        {
                            loader: "file-loader",
                            options: {
                                outputPath: 'images'
                            }
                        }
                    ]
                },
                {
                    test: /\.(woff|woff2|ttf|otf|eot)$/,
                    use: [
                        {
                            loader: "file-loader",
                            options: {
                                outputPath: 'fonts'
                            }
                        }
                    ]
                }
            ]
        },

        plugins: [
            new MiniCssExtractPlugin({
                filename: devMode ? '[name].css' : '[name].[hash].css',
            }),
            new BrowserSyncPlugin({
                proxy: 'https://dev.identity/oauth/authorize?response_type=code&client_id=1c9e2b58-2d01-4c92-a603-c934dfa9bc78&redirect_uri=https://localhost/hooray&state=aaaaa&code_challenge=12345678901234567890123456789012345678901123&code_challenge_method=plain&resource=https://cloud.ctdxapis.io&scope=cloud:my-profile'
            }),
            new CopyPlugin([
                { from: './resources/images', to: './images' }
            ]),
            new HtmlWebpackPlugin({

            }),
        ]
    };
};

更新后的结构:

HtmlWebpackPlugin将bundle.[hash].js/css加载到基础twig文件中。

英文:

I have two entries in my webpack.config.js. One for the JS and one for the SCSS. I can run in development and product mode. If i create a production build I get the following files: index.html, main[hash].js, main[hash].css. In the index.html i have the link and script tag with the src to the files. How do i load these link & script tags in my base.twig file that get loaded when deploying the application?
In development it loads the main.js from the base.twig and in that file everything is included.

base.twig

&lt;script src=&quot;assets/main.js&quot;&gt;&lt;/script&gt;

Folder structure:

HtmlWebpackPlugin将bundle.[hash].js/css加载到基础twig文件中。

index.html

&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;title&gt;Webpack App&lt;/title&gt;
&lt;link href=&quot;main.7a67bd4eae959f87c9bc.css&quot; rel=&quot;stylesheet&quot;&gt;&lt;/head&gt;
&lt;body&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;main.7a67bd4eae959f87c9bc.js&quot;&gt;&lt;/script&gt;&lt;/body&gt;
&lt;/html&gt;

webpack.config.js

const path = require(&#39;path&#39;);
const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);
const MiniCssExtractPlugin = require(&quot;mini-css-extract-plugin&quot;);
const BrowserSyncPlugin = require(&#39;browser-sync-webpack-plugin&#39;);
const CopyPlugin = require(&#39;copy-webpack-plugin&#39;);
module.exports = (env, options) =&gt; {
const devMode = options.mode === &#39;development&#39;;
return {
mode: (devMode) ? &#39;development&#39; : &#39;production&#39;,
watch: devMode,
devtool: &quot;source-map&quot;,
entry: [
&#39;./resources/javascript/index.js&#39;,
&#39;./resources/sass/app.scss&#39;
],
output: {
path: path.resolve(__dirname, &#39;public/assets&#39;),
filename: devMode ? &#39;[name].js&#39; : &#39;[name].[hash].js&#39;
},
module: {
rules: [
{
test:   /\.twig/,
loader: &#39;twig-loader&#39;
},
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: &#39;babel-loader&#39;,
options: {
presets: [&#39;@babel/preset-env&#39;]
}
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: devMode ? &#39;style-loader&#39; : MiniCssExtractPlugin.loader,
},
{
loader: &quot;css-loader&quot;,
},
{
loader: &quot;postcss-loader&quot;
},
{
loader: &quot;sass-loader&quot;,
options: {
implementation: require(&quot;sass&quot;)
}
}
]
},
{
test: /\.(png|jpe?g|gif|svg)$/,
use: [
{
loader: &quot;file-loader&quot;,
options: {
outputPath: &#39;images&#39;
}
}
]
},
{
test: /\.(woff|woff2|ttf|otf|eot)$/,
use: [
{
loader: &quot;file-loader&quot;,
options: {
outputPath: &#39;fonts&#39;
}
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: devMode ? &#39;[name].css&#39; : &#39;[name].[hash].css&#39;,
}),
new BrowserSyncPlugin({
proxy: &#39;https://dev.identity/oauth/authorize?response_type=code&amp;client_id=1c9e2b58-2d01-4c92-a603-c934dfa9bc78&amp;redirect_uri=https://localhost/hooray&amp;state=aaaaa&amp;code_challenge=12345678901234567890123456789012345678901123&amp;code_challenge_method=plain&amp;resource=https://cloud.ctdxapis.io&amp;scope=cloud:my-profile&#39;
}),
new CopyPlugin([
{ from: &#39;./resources/images&#39;, to: &#39;./images&#39; }
]),
new HtmlWebpackPlugin({
}),
]
};
};

Updated structure:
HtmlWebpackPlugin将bundle.[hash].js/css加载到基础twig文件中。

答案1

得分: 1

你可以提供HTMLWebpackPlugintemplateContent配置属性,以生成你的assets.twig文件。

new HtmlWebpackPlugin({
  templateContent: function(params) {
    return `
    {% block jsAssets %}
      ${params.htmlWebpackPlugin.files.js.map(
        file => `<script src="${file}"></script>`,
      )}
    {% endblock %}

    {% block cssAssets %}
      ${params.htmlWebpackPlugin.files.css.map(
         file => `<link rel="stylesheet" type="text/css" href="${file}">`,
       )}
    {% endblock %}`;
  },
  filename: '../../resources/templates/assets.twig',
  inject: false, // 防止插件自动注入HTML标签
});

然后在你的base.twig中,使用blocks方法来指定渲染你的资源位置。

{{ block("jsAssets", "assets.twig") }}
{{ block("cssAssets", "assets.twig") }}
英文:

You can provide templateContent config property of HTMLWebpackPlugin in-order to generate your assets.twig file

new HtmlWebpackPlugin({
  templateContent: function(params) {
    return `
    {% block jsAssets %}
      ${params.htmlWebpackPlugin.files.js.map(
        file =&gt; `&lt;script src=&quot;${file}&quot;&gt;&lt;/script&gt;`,
      )}
    {% endblock %}

    {% block cssAssets %}
      ${params.htmlWebpackPlugin.files.css.map(
         file =&gt; `&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;${file}&quot;&gt;`,
       )}
    {% endblock %}`;
  },
  filename: &#39;../../resources/templates/assets.twig&#39;,
  inject: false, // prevents from the plugin to auto-inject html tags
});

Then in your base.twig just use the blocks method to specify where to render your assets.

{{ block(&quot;jsAssets&quot;, &quot;assets.twig&quot;) }}
{{ block(&quot;cssAssets&quot;, &quot;assets.twig&quot;) }}

huangapple
  • 本文由 发表于 2020年1月6日 17:23:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定