Multiple html files using webpack

前端 未结 5 511
谎友^
谎友^ 2020-12-07 09:01

I\'m trying to do something in a project that I\'m not sure if it is possible, I am in a wrong way or misunderstanding something. We are using webpack, and the idea is to se

5条回答
  •  天涯浪人
    2020-12-07 09:47

    There is another solution, assuming Webpack ^4.44.1. That is, importing the HTML in your JS/TS app.

    Sample webpack.config.js

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const { CleanWebpackPlugin } = require('clean-webpack-plugin');
    
    
    module.exports = {
        entry: { app: './src/index.ts' },
    
        mode: 'development',
        devtool: 'inline-source-map',
        plugins: [
            new CleanWebpackPlugin(),
            new HtmlWebpackPlugin({
                title: 'Development',
                template: path.join(path.resolve(__dirname, 'src'), 'index.ejs')
            }),
        ],
        module: {
            rules: [
                {
                    test: /\.ts$/,
                    use: 'ts-loader',
                    include: [path.resolve(__dirname, 'src')],
                    exclude: /node_modules/,
                },
                {
                    test: /\.html$/i,
                    use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name: '[name].[ext]'
                            }
                        }
                    ],
                    // this exclude is required
                    exclude: path.join(path.resolve(__dirname, 'src'), 'index.html')
                }
            ],
        },
        resolve: {
            extensions: ['.ts', '.js'],
        },
        devServer: {
            contentBase: path.join(__dirname, 'dist'),
            compress: true,
            port: 3900
        },
        output: {
            filename: 'bundle.js',
            path: path.resolve(__dirname, 'dist'),
        },
    };
    

    Corresponding app

    import './about.html';
        
    console.log('this is a test'); 
    

    index.ejs

    
    
    
        
        Question
    
    
         About
    
    
    

    about.html

    
    
    
        
        
        About
    
    
        

    This is an about page

    Webpack will copy about.html to the corresponding output folder.

提交回复
热议问题