Skip to content

Feat/filename transform #321

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,17 @@ module.exports = {
}
```

#### Filename as function instead of string

By using a function instead of a string, you can use chunk data to customize the filename. This is particularly useful when dealing with multiple entry points and wanting to get more control out of the filename for a given entry point/chunk. In the example below, the we'll change the filename to output the css to a different directory.

```javascript
const miniCssExtractPlugin = new MiniCssExtractPlugin({
filename: ({ name, chunkhash }) =>
`${name.replace('/js/', '/css/')}.[chunkhash:8].css`
})
```

#### Long Term Caching

For long term caching use `filename: "[contenthash].css"`. Optionally add `[name]`.
Expand Down
28 changes: 21 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 10 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const pluginName = 'mini-css-extract-plugin';
const REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/i;
const REGEXP_CONTENTHASH = /\[contenthash(?::(\d+))?\]/i;
const REGEXP_NAME = /\[name\]/i;
const REGEXP_PLACEHOLDERS = /\[(name|id|chunkhash)\]/g;
const DEFAULT_FILENAME = '[name].css';

class CssDependency extends webpack.Dependency {
constructor(
Expand Down Expand Up @@ -112,21 +114,18 @@ class MiniCssExtractPlugin {
constructor(options) {
this.options = Object.assign(
{
filename: '[name].css',
filename: DEFAULT_FILENAME,
},
options
);
if (!this.options.chunkFilename) {
const { filename } = this.options;
const hasName = filename.includes('[name]');
const hasId = filename.includes('[id]');
const hasChunkHash = filename.includes('[chunkhash]');
// Anything changing depending on chunk is fine
if (hasChunkHash || hasName || hasId) {
if (typeof filename === 'string' && REGEXP_PLACEHOLDERS.test(filename)) {
this.options.chunkFilename = filename;
} else {
// Elsewise prefix '[id].' in front of the basename to make it changing
this.options.chunkFilename = filename.replace(
this.options.chunkFilename = DEFAULT_FILENAME.replace(
/(^|\/)([^/]*(?:\?|$))/,
'$1[id].$2'
);
Expand Down Expand Up @@ -170,6 +169,10 @@ class MiniCssExtractPlugin {
const renderedModules = Array.from(chunk.modulesIterable).filter(
(module) => module.type === MODULE_TYPE
);
const { filename } = this.options;
const filenameTemplate =
typeof filename === 'function' ? filename(chunk) : filename;

if (renderedModules.length > 0) {
result.push({
render: () =>
Expand All @@ -179,7 +182,7 @@ class MiniCssExtractPlugin {
renderedModules,
compilation.runtimeTemplate.requestShortener
),
filenameTemplate: this.options.filename,
filenameTemplate,
pathOptions: {
chunk,
contentHashType: MODULE_TYPE,
Expand Down
147 changes: 87 additions & 60 deletions test/TestCases.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,71 +9,98 @@ describe('TestCases', () => {
for (const directory of fs.readdirSync(casesDirectory)) {
if (!/^(\.|_)/.test(directory)) {
// eslint-disable-next-line no-loop-func
it(`${directory} should compile to the expected result`, (done) => {
const directoryForCase = path.resolve(casesDirectory, directory);
const outputDirectoryForCase = path.resolve(outputDirectory, directory);
// eslint-disable-next-line import/no-dynamic-require, global-require
const webpackConfig = require(path.resolve(
directoryForCase,
'webpack.config.js'
));
for (const config of [].concat(webpackConfig)) {
Object.assign(
config,
{
mode: 'none',
context: directoryForCase,
output: Object.assign(
{
path: outputDirectoryForCase,
},
config.output
),
},
config
it(
`${directory} should compile to the expected result`,
(done) => {
const directoryForCase = path.resolve(casesDirectory, directory);
const outputDirectoryForCase = path.resolve(
outputDirectory,
directory
);
}
webpack(webpackConfig, (err, stats) => {
if (err) {
done(err);
return;
}
done();
// eslint-disable-next-line no-console
console.log(
stats.toString({
context: path.resolve(__dirname, '..'),
chunks: true,
chunkModules: true,
modules: false,
})
);
if (stats.hasErrors()) {
done(
new Error(
stats.toString({
context: path.resolve(__dirname, '..'),
errorDetails: true,
})
)
// eslint-disable-next-line import/no-dynamic-require, global-require
const webpackConfig = require(path.resolve(
directoryForCase,
'webpack.config.js'
));
for (const config of [].concat(webpackConfig)) {
Object.assign(
config,
{
mode: 'none',
context: directoryForCase,
output: Object.assign(
{
path: outputDirectoryForCase,
},
config.output
),
},
config
);
return;
}
const expectedDirectory = path.resolve(directoryForCase, 'expected');
for (const file of fs.readdirSync(expectedDirectory)) {
const content = fs.readFileSync(
path.resolve(expectedDirectory, file),
'utf-8'
webpack(webpackConfig, (err, stats) => {
if (err) {
done(err);
return;
}
done();
// eslint-disable-next-line no-console
console.log(
stats.toString({
context: path.resolve(__dirname, '..'),
chunks: true,
chunkModules: true,
modules: false,
})
);
const actualContent = fs.readFileSync(
path.resolve(outputDirectoryForCase, file),
'utf-8'
if (stats.hasErrors()) {
done(
new Error(
stats.toString({
context: path.resolve(__dirname, '..'),
errorDetails: true,
})
)
);
return;
}
const expectedDirectory = path.resolve(
directoryForCase,
'expected'
);
expect(actualContent).toEqual(content);
}
done();
});
}, 10000);

for (const file of walkSync(expectedDirectory)) {
const actualFilePath = file.replace(
new RegExp(`/cases/${directory}/expected/`),
`/js/${directory}/`
);
const expectedContent = fs.readFileSync(file, 'utf-8');
const actualContent = fs.readFileSync(actualFilePath, 'utf-8');

expect(actualContent).toEqual(expectedContent);
}
done();
});
},
10000
);
}
}
});

/**
* Synchronously traverse directory of files
* @param {String} dir
* @returns {String} path to file or directory
*/
function* walkSync(dir) {
for (const file of fs.readdirSync(dir)) {
const pathToFile = path.join(dir, file);
const isDirectory = fs.statSync(pathToFile).isDirectory();
if (isDirectory) {
yield* walkSync(pathToFile);
} else {
yield pathToFile;
}
}
}
2 changes: 2 additions & 0 deletions test/cases/filename/expected/demo/css/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
body { background: purple; }

1 change: 1 addition & 0 deletions test/cases/filename/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import './style.css';
1 change: 1 addition & 0 deletions test/cases/filename/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
body { background: purple; }
24 changes: 24 additions & 0 deletions test/cases/filename/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const Self = require('../../../');

module.exports = {
entry: {
'demo/js/main': './index.js',
},
module: {
rules: [
{
test: /\.css$/,
use: [Self.loader, 'css-loader'],
},
],
},
output: {
filename: '[name].js',
},
plugins: [
new Self({
filename: ({ name }) =>
`${name.replace('/js/', '/css/')}.css`,
}),
],
};