Skip to content

Webpack

Chaos edited this page Jul 20, 2020 · 5 revisions

Webpack

webpack能把所有的JS打包成一个JS文件,并能支持最新的JS特性,是现代化JS编程的一个重要工具。本项目的模板已经有一份配置,默认为根目录下的webpack.config.js

webpack.config.js

const path = require("path")
const JavascriptObfuscator = require("webpack-obfuscator")
const AutoProWebpackPlugin = require('@auto.pro/webpack-plugin')

const dictionary = []
for (let i = 1024; i < 2048; i++) {
    dictionary.push(i.toString(2).replace(/1/g, "ν").replace(/0/g, "v")) 
}

module.exports = {
    entry: {
        app: path.resolve(__dirname, "../src/index.js"),
    },
    // devtool: 'sourcemap',
    output: {
        filename: "[name].js",
        path: path.resolve(__dirname, "../dist"),
        // libraryTarget: "commonjs2",
        libraryTarget: "var",
    },
    target: "node",
    mode: "production",
    plugins: [
        new JavascriptObfuscator({
            compact: true,
            identifierNamesGenerator: "dictionary",
            identifiersDictionary: dictionary,
            target: "browser-no-eval",
            unicodeEscapeSequence: false,
            transformObjectKeys: true,
        }),
        new AutoProWebpackPlugin({
            ui: ['app'],
            encode: {
                key: "SecretPassphrase"
            }
        })
    ],
    module: {
        rules: [
            {
                test: /\.ts$/,
                exclude: /node_modules/,
                use: {
                    loader: "ts-loader",
                },
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                },
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: {
                    loader: "url-loader",
                },
            },
        ],
    },
    resolve: {
        extensions: [".js", ".ts", ".json"],
        alias: {
            "@": path.resolve(__dirname, "../src"),
        },
    },
}

webpack-obfuscator

webpack-obfuscator插件提供了代码混淆的功能,详情请看webpack-obfuscator

@auto.pro/webpack-plugin

此插件提供了auto.pro的UI模式打包,并能进行AES代码加密,它有两个很简单的配置项

  • ui: string[] 将数组内的文件进行UI模式打包,文件名对应webpack.config.js文件的entry
  • encode: { key: string } 将所有文件进行加密输出,key为AES密钥,当encode缺省时不进行加密

output.libraryTarget

webpack提供了多种文件输出格式,如果你需要打包成可引入的格式,也就是按项目方式运行,则需要将libraryTarget设置成commonjs2,比如这样的引入:

//main.js
require('dist/app')

如果你希望打包的文件能直接以单个脚本方式运行,则将libraryTarget设置为var

Clone this wiki locally