Is it possible to strip special characters from fi

2019-06-22 01:45发布

问题:

Long story short, I cannot have certain characters like hyphens in our asset filenames. I'm not having the best of luck parsing through webpack documentation to figure out if it is possible to rename a file using a regex or something similar so I can strip out any hyphens from 3rd party packages where I do not control the source filename.

My super naive example would be something like this:

{
    test: /\.(ttf|eot|woff|woff2)$/,
    loader: `url-loader?limit=${ASSETS_LIMIT}&name=fonts/[name.replace(/-/)].[ext]`
}

Does anyone know if this is possible or how one would approach this requirement? Thanks!

回答1:

The answer to this riddle appears to be found in the customInterpolateName loader option. With webpack@v3.4.1 the below was my end result for removing a hyphen.

This was the key tidbit:

plugins: [
    // ... other plugins ...
    new webpack.LoaderOptionsPlugin({
        options: {
            customInterpolateName: (loaderContext) => {
                return loaderContext.replace(/-/g, '');
            }
        }
    })
]

Here's a more complete example to give some context (note: the .css was appended to the font filenames intentionally as a workaround for yet another web resource name restriction in Dynamics CRM):

module.exports = {
    // ... other config ...
    module: {
        loaders: [
            // ... other loaders ...
            {
                test: /\.(ttf|eot|woff|woff2)$/,
                loader: `url-loader?limit=${ASSETS_LIMIT}&name=fonts/[name].[ext].css`
            }
        ]
    },

    plugins: [
        // ... other plugins ...
        new webpack.LoaderOptionsPlugin({
            options: {
                customInterpolateName: (loaderContext) => {
                    return loaderContext.replace(/-/g, '');
                }
            }
        })
    ]
};