首页 > 解决方案 > Webpack 不会将 javascript 注入到 cshtml

问题描述

嗨,我有一个 MVC 5 项目,其中包含大量 JavaScript 前端代码。所以我决定模块化这些 javascript ==> 将它们注入 cshtml 模板 ==> 在我的 View My 配置中渲染部分它们:

webpack.config.js

module.exports = {
entry: {
    layout: './Public/js/Layout.js', 
    index: './ViewModules/Home/Index.js',
    noisoisieuam: './ViewModules/KetQua/NoiSoiSieuAm.js'
},
output: {
    path: path.resolve(__dirname, './Public/Output'),
    filename: '[name].bundle.[contenthash].js',
},
plugins: [
    new HtmlWebpackPlugin({
        inject: true,
        templateContent: '',
        filename: '../../../ViewModules/Shared/_Layout.temp.cshtml',
        chunks: [ 'layout']
    }),
    new HtmlWebpackPlugin({
        inject: true, 
        templateContent: '',
        filename: '../../../ViewModules/Home/Index.temp.cshtml',
        chunks: ['index']
    }),
    new HtmlWebpackPlugin({
        inject: true, 
        templateContent: '',
        filename: '../../../ViewModules/KetQua/NoiSoiSieuAm.temp.cshtml',
        chunks: ['noisoisieuam']
    })
],
// IMPORTANT NOTE: If you are using Webpack 2 or above, replace "loaders" with "rules"
module: {
    rules: [
        {
            use: [
                {
                    loader: 'babel-loader',
                    options: {
                        presets: ["@babel/preset-env"]
                        }
                }
            ],
            test: /\.js$/,
            exclude: /node_modules/
        },
        {
            test: /\.json$/,
            type: 'javascript/auto',
            use: [
                {
                    loader: 'file-loader',
                    options: {
                        name: "[path][name].[ext]"
                    }
                }
            ],                
        }
    ]
}

}

这些*.temp.cshtml文件是空的 cshtml 文件,仅用于 javascript 注入。我各自*.cshtml(我的观点)中的代码:

    ...
@Html.Partial("~/ViewModules/<path-to-template>/*.temp.cshtml")
...

问题是只有前 2 个 temp.cshtml 是由 webpack (_Layout和我的主页)注入的。

npm run build或在 Visual Studio 中构建不要给出任何错误。那些 javascript 包都创建了。该'noisoisieuam'块未注入到我的 temp.cshtml

我怎样才能解决这个问题?非常感谢

标签: javascriptasp.net-mvcwebpackhtml-webpack-plugin

解决方案


推荐阅读