Webpack 将JavaScript代码内联在HTML页面

前端

Winter

2018-07-19

这次要介绍一个插件html-webpack-inline-source-plugin,它其实是html-webpack-plugin的一个扩展。而我们需要Webpack 将JavaScript代码内联在HTML页面时就需要使用到它了。

1.首先,安装插件,我们同时也需要intstall  html-webpack-plugin

npm install --save-dev html-webpack-plugin html-webpack-inline-source-plugin

2.使用方法

在你的webpack config文件中引入

var HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');

然后将其添加至你的plugins数组中,例如:


plugins: [  
    new HtmlWebpackPlugin(),
    new HtmlWebpackInlineSourcePlugin()
]

但是仅仅是这样添加,那是不够的,这时候需要同时设置HtmlWebpackPlugin,我们需要设置HtmlWebpackPlugin的属性,增加一个 inlineSource 选项来匹配 css 和 js ,最终才会将资源内联到 html 中。


plugins: [  
    new HtmlWebpackPlugin({
        inlineSource: '.(js&|css)$' // 内联所有 javascript、css。
    }),  
    new HtmlWebpackInlineSourcePlugin()
]

下面贴一个完整的示例:


var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require("html-webpack-plugin");
var HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
var UglifyJSPlugin = require('uglifyjs-webpack-plugin')

var serverConfig = {
    mode: "development",
    plugins: [new webpack.DefinePlugin({
            "global.GENTLY": false,
        }),
        new HtmlWebpackPlugin({
            inject: true,
            minify: {
                //压缩HTML文件
                removeComments: true, //移除HTML中的注释
                collapseWhitespace: false, //删除空白符与换行符
                removeAttributeQuotes: true//压缩 去掉引号
            },
            template: "./template/index.html",
            filename: "SamYoc_Trade.html",
            minify: true,
            inlineSource: '.(js|css)'
        }),
        new HtmlWebpackInlineSourcePlugin(),
        new UglifyJSPlugin({
            parallelization: true,
        })
    ],
    entry: {
        server: "./app.js"
    },
    target: 'node',
    node: {
        __filename: true,
        __dirname: true
    },
    output: {
        path: path.resolve(__dirname, '../dist'),
        filename: '[name].js',
        chunkFilename: '[name].chunk.js'
    },
    module: {
        rules: [{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: 'babel-loader'
        }, {
            test: /.(svg|png|jpg|jpeg|otf|gif)$/,
            exclude: /node_modules/,
            use: 'url?limit=10'
        }]
    },
    // externals: getExternals(),
    resolve: {
        extensions: ['.js', '.jsx', '.less', '.css', '.json']
    }
};

module.exports = serverConfig;

第74篇《Webpack 将JavaScript代码内联在HTML页面》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0条评论