Как использовать пакетный JavaScript в теге HTML-скрипта - PullRequest
0 голосов
/ 10 ноября 2019

Я обновляю веб-приложение до ASP.NET Core 3.0. Одна из задач, которую я планировал долгое время, - использовать современный пакет, такой как webpack. Я думаю, что обработал все случаи, несмотря на потребление кода JavaScript внутри тега <script>.

Если вы уже знакомы с вещами ASP.NET, вы можете просто пропустить их. Этот вопрос также применим к простому HTML.

Ошибка, которую я всегда получаю после просмотра веб-сайта:
Uncaught SyntaxError: The requested module './dist/bundle.js' does not provide an export named 'exampleSite'

. / Ts / example / index. ts

export default () => {
  console.log('example site's init script has been called.');
}

bundle_body.js

import 'moment';
import 'jquery';
window.jQuery = $;
window.$ = $;
window.jquery = $;
import exampleSite from './ts/Example/index.ts'
// Exportet content from the bundle is also no working
// export { exampleSite}

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = (env = {}, argv = {}) => {

    const isProd = argv.mode === 'production';

    const config = {
        mode: argv.mode || 'development', // we default to development when no 'mode' arg is passed

        optimization: {
            minimize: true
        },
        entry: {
            head: './wwwroot/src/bundle_head.js',
            body: './wwwroot/src/bundle_body.js',
            css: './wwwroot/src/bundle_css.js'
        },
        output: {
            filename: isProd ? 'bundle-[chunkHash].js' : '[name].js',
            path: path.resolve(__dirname, './wwwroot/dist'),
            publicPath: "/dist/"
        },
        plugins: [
            new MiniCssExtractPlugin({
                filename: isProd ? 'style-[contenthash].css' : 'style.css'
            }),
            new CompressionPlugin({
                filename: '[path].gz[query]',
                algorithm: 'gzip',
                test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
                threshold: 10240,
                minRatio: 0.8
            }),
            new HtmlWebpackPlugin({
                chunks: ['head', 'body', 'css'],
                template: './Views/Shared/_LayoutTemplate.cshtml',
                filename: '../../Views/Shared/_Layout.cshtml',       
                inject: false
            })
        ],
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader"
                    }
                },
                {
                    test: /\.ts$/,
                    exclude: /node_modules/,
                    use: 'ts-loader'
                },
                {
                    test: /\.(sa|sc|c)ss$/,
                    use: [
                        'style-loader',
                        MiniCssExtractPlugin.loader,
                        'css-loader',
                        'sass-loader'
                    ]
                },
                {
                    test: /\.(png|jpg|gif|woff|woff2|eot|ttf|svg)$/,
                    loader: 'file-loader',
                    options: {
                        name: '[name].[hash].[ext]',
                        outputPath: 'assets/'
                    }
                }
            ]
        }
    };
    return config;
};

Layout.cshtml

<html>
  <head>
    <link href="<%= htmlWebpackPlugin.files.chunks.css.css %>" rel="stylesheet" />
    <script src="<%= htmlWebpackPlugin.files.chunks.head.entry %>"></script>
  </head>
  <body>
    ...

    <script src="<%= htmlWebpackPlugin.files.chunks.body.entry %>" type="module"></script>

    @RenderSection("Scripts", required: false)    
  </body
</html>

Index.cshtml

<div>
  ...
</div>

@section Scripts
{
    <script type="module">
        import exampleSite from './dist/body.js'

        exampleIndex();
    </script>
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...