//webpack.configuration.js
/**
* @file Webpack configuration.
*/
const path = require('path');
const generateScopedName = (localName, resourcePath) => {
const componentName = resourcePath.split('/').slice(-2, -1);
return componentName + '_' + localName;
};
module.exports = {
module: {
rules: [
{
include: path.resolve(__dirname, '../app'),
loader: 'babel-loader',
options: {
babelrc: false,
extends: path.resolve(__dirname, '../app/webpack.production.babelrc'),
plugins: [
[
'react-css-modules',
{
context: common.context,
filetypes: {
'.scss': {
syntax: 'postcss-scss'
}
},
generateScopedName,
webpackHotModuleReloading: false
}
]
]
},
test: /\.js$/
},
{
test: /\.scss$/,
use: [
{
loader: 'css-loader',
options: {
camelCase: true,
getLocalIdent: (context, localIdentName, localName) => {
return generateScopedName(localName, context.resourcePath);
},
importLoaders: 1,
minimize: true,
modules: true
}
},
'resolve-url-loader'
]
}
]
},
output: {
filename: '[name].[chunkhash].js',
path: path.join(__dirname, './.dist'),
publicPath: '/static/'
},
stats: 'minimal'
};
``````````````````````````````````
缩短命名
//createUniqueIdGenerator.js
const incstr = require('incstr');
const createUniqueIdGenerator = () => {
const index = {};
const generateNextId = incstr.idGenerator({
// Removed "d" letter to avoid accidental "ad" construct.
// @see https://medium.com/@mbrevda/just-make-sure-ad-isnt-being-used-as-a-class-name-prefix-or-you-might-suffer-the-wrath-of-the-558d65502793
alphabet: 'abcefghijklmnopqrstuvwxyz0123456789'
});
return (name) => {
if (index[name]) {
return index[name];
}
let nextId;
do {
// Class name cannot start with a number.
nextId = generateNextId();
} while (/^[0-9]/.test(nextId));
index[name] = generateNextId();
return index[name];
};
};
const uniqueIdGenerator = createUniqueIdGenerator();
const generateScopedName = (localName, resourcePath) => {
const componentName = resourcePath.split('/').slice(-2, -1);
return uniqueIdGenerator(componentName) + '_' + uniqueIdGenerator(localName);
};
``````````````````````````````````
使用作用域隔离进一步压缩文件束体积
//getScopes.js
const getScopes = (ast) => {
const scopes = {};
const getModuleID = (className) => {
const tokens = className.split('_')[0];
if (tokens.length !== 2) {
return 'default';
}
return tokens[0];
};
csso.syntax.walk(ast, node => {
if (node.type === 'ClassSelector') {
const moduleId = getModuleID(node.name);
if (moduleId) {
if (!scopes[moduleId]) {
scopes[moduleId] = [];
}
if (!scopes[moduleId].includes(node.name)) {
scopes[moduleId].push(node.name);
}
}
}
});
return Object.values(scopes);
};