diff --git a/README.md b/README.md index b1504f89..19c3cec2 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,7 @@ module.exports = { | **[`localsConvention`](#localsconvention)** | `{String}` | `'asIs'` | Style of exported classnames | | **[`onlyLocals`](#onlylocals)** | `{Boolean}` | `false` | Export only locals | | **[`esModule`](#esmodule)** | `{Boolean}` | `false` | Use ES modules syntax | +| **[`exportNamed`](#exportNamed)** | `{Boolean}` | `false` | Use ES modules named export | ### `url` @@ -1035,6 +1036,55 @@ module.exports = { }; ``` +### `exportNamed` + +Type: `Boolean` +Default: `false` + +Enable/disable ES modules named export for css classes. +Names of exported classes are converted to camelCase. + +**styles.css** + +```css +.foo-baz { + color: red; +} +.bar { + color: blue; +} +``` + +**index.js** + +```js +import { fooBaz, bar } from './styles.css'; + +console.log(fooBaz, bar); +``` + +You can enable a ES module named export using: + +**webpack.config.js** + +```js +module.exports = { + module: { + rules: [ + { + test: /\.css$/i, + loader: 'css-loader', + options: { + esModule: true, + modules: true, + exportNamed: true, + }, + }, + ], + }, +}; +``` + ## Examples ### Assets diff --git a/src/index.js b/src/index.js index 94e33b52..86302523 100644 --- a/src/index.js +++ b/src/index.js @@ -171,11 +171,33 @@ export default function loader(content, map, meta) { ); }); - const { localsConvention } = options; + const exportNamed = + typeof options.exportNamed !== 'undefined' + ? options.exportNamed + : false; + + const { localsConvention } = exportNamed + ? { localsConvention: 'camelCaseOnly' } + : options; + const esModule = typeof options.esModule !== 'undefined' ? options.esModule : false; - const importCode = getImportCode(this, exportType, imports, esModule); + if (Boolean(exportNamed) && Boolean(exportNamed) !== Boolean(esModule)) { + this.emitError( + new Error( + '`Options.exportNamed` can not use without `options.esModule`' + ) + ); + } + + const importCode = getImportCode( + this, + exportType, + imports, + esModule, + exportNamed + ); const moduleCode = getModuleCode( result, exportType, @@ -183,14 +205,16 @@ export default function loader(content, map, meta) { apiImports, urlReplacements, icssReplacements, - esModule + esModule, + exportNamed ); const exportCode = getExportCode( exports, exportType, localsConvention, icssReplacements, - esModule + esModule, + exportNamed ); return callback(null, `${importCode}${moduleCode}${exportCode}`); diff --git a/src/options.json b/src/options.json index 43ac0f9c..727c8c3c 100644 --- a/src/options.json +++ b/src/options.json @@ -121,6 +121,10 @@ "esModule": { "description": "Use the ES modules syntax (https://github.com/webpack-contrib/css-loader#esmodule).", "type": "boolean" + }, + "exportNamed": { + "description": "Use the named export ES modules.", + "type": "boolean" } }, "type": "object" diff --git a/src/plugins/postcss-icss-parser.js b/src/plugins/postcss-icss-parser.js index f2de17ba..bc800625 100644 --- a/src/plugins/postcss-icss-parser.js +++ b/src/plugins/postcss-icss-parser.js @@ -83,6 +83,7 @@ export default postcss.plugin( value: { // 'CSS_LOADER_ICSS_IMPORT' order: 0, + icss: true, importName, url: options.urlHandler(resolvedUrl), index: currentIndex, diff --git a/src/utils.js b/src/utils.js index 5edcbc34..3807f617 100644 --- a/src/utils.js +++ b/src/utils.js @@ -258,7 +258,13 @@ function getPreRequester({ loaders, loaderIndex }) { }; } -function getImportCode(loaderContext, exportType, imports, esModule) { +function getImportCode( + loaderContext, + exportType, + imports, + esModule, + exportNamed +) { let code = ''; if (exportType === 'full') { @@ -273,10 +279,12 @@ function getImportCode(loaderContext, exportType, imports, esModule) { } for (const item of imports) { - const { importName, url } = item; + const { importName, url, icss } = item; code += esModule - ? `import ${importName} from ${url};\n` + ? icss && exportNamed + ? `import ${importName}, * as ${importName}_NAMED___ from ${url};\n` + : `import ${importName} from ${url};\n` : `var ${importName} = require(${url});\n`; } @@ -290,7 +298,8 @@ function getModuleCode( apiImports, urlReplacements, icssReplacements, - esModule + esModule, + exportNamed ) { if (exportType !== 'full') { return 'var ___CSS_LOADER_EXPORT___ = {};\n'; @@ -339,9 +348,12 @@ function getModuleCode( for (const replacement of icssReplacements) { const { replacementName, importName, localName } = replacement; - code = code.replace( - new RegExp(replacementName, 'g'), - () => `" + ${importName}.locals[${JSON.stringify(localName)}] + "` + code = code.replace(new RegExp(replacementName, 'g'), () => + exportNamed + ? `" + ${importName}_NAMED___[${JSON.stringify( + camelCase(localName) + )}] + "` + : `" + ${importName}.locals[${JSON.stringify(localName)}] + "` ); } @@ -359,10 +371,12 @@ function getExportCode( exportType, localsConvention, icssReplacements, - esModule + esModule, + exportNamed ) { let code = ''; let localsCode = ''; + let namedCode = ''; const addExportToLocalsCode = (name, value) => { if (localsCode) { @@ -370,6 +384,10 @@ function getExportCode( } localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`; + + if (exportNamed) { + namedCode += `export const ${name} = ${JSON.stringify(value)};\n`; + } }; for (const { name, value } of exports) { @@ -416,10 +434,22 @@ function getExportCode( new RegExp(replacementName, 'g'), () => `" + ${importName}.locals[${JSON.stringify(localName)}] + "` ); + + if (exportNamed) { + namedCode = namedCode.replace( + new RegExp(replacementName, 'g'), + () => + `" + ${importName}_NAMED___[${JSON.stringify( + camelCase(localName) + )}] + "` + ); + } } if (localsCode) { - code += `___CSS_LOADER_EXPORT___.locals = {\n${localsCode}\n};\n`; + code += namedCode + ? `${namedCode}\n` + : `___CSS_LOADER_EXPORT___.locals = {\n${localsCode}\n};\n`; } code += `${ diff --git a/test/__snapshots__/esModule-option.test.js.snap b/test/__snapshots__/esModule-option.test.js.snap index f70bc872..9345a3aa 100644 --- a/test/__snapshots__/esModule-option.test.js.snap +++ b/test/__snapshots__/esModule-option.test.js.snap @@ -1,5 +1,68 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`"esModule" option should emit error when class has unsupported name: errors 1`] = ` +Array [ + "ModuleParseError: Module parse failed: Unexpected keyword 'class' (7:13) +File was processed with these loaders:", +] +`; + +exports[`"esModule" option should emit error when class has unsupported name: warnings 1`] = `Array []`; + +exports[`"esModule" option should emit error when exportNamed true && esModule false: errors 1`] = ` +Array [ + "ModuleError: Module Error (from \`replaced original path\`): +\`Options.exportNamed\` can not use without \`options.esModule\`", +] +`; + +exports[`"esModule" option should work js template with "exportNamed" option: errors 1`] = `Array []`; + +exports[`"esModule" option should work js template with "exportNamed" option: module 1`] = ` +"// Imports +import ___CSS_LOADER_API_IMPORT___ from \\"../../../../../src/runtime/api.js\\"; +var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(false); +// Module +___CSS_LOADER_EXPORT___.push([module.id, \\".header-baz {\\\\n color: red;\\\\n}\\\\n\\\\n.body {\\\\n color: coral;\\\\n}\\\\n\\\\n.footer {\\\\n color: blue;\\\\n}\\\\n\\", \\"\\"]); +// Exports +export const headerBaz = \\"header-baz\\"; +export const body = \\"body\\"; +export const footer = \\"footer\\"; + +export default ___CSS_LOADER_EXPORT___; +" +`; + +exports[`"esModule" option should work js template with "exportNamed" option: result 1`] = ` +Object { + "css": Array [ + Array [ + "./es-module/named/template/index.css", + ".header-baz { + color: red; +} + +.body { + color: coral; +} + +.footer { + color: blue; +} +", + "", + ], + ], + "html": " +
+
+
+", +} +`; + +exports[`"esModule" option should work js template with "exportNamed" option: warnings 1`] = `Array []`; + exports[`"esModule" option should work when not specified: errors 1`] = `Array []`; exports[`"esModule" option should work when not specified: module 1`] = ` @@ -46,6 +109,79 @@ Array [ exports[`"esModule" option should work when not specified: warnings 1`] = `Array []`; +exports[`"esModule" option should work with "exportNamed" option with nested import: errors 1`] = `Array []`; + +exports[`"esModule" option should work with "exportNamed" option with nested import: module 1`] = ` +"// Imports +import ___CSS_LOADER_API_IMPORT___ from \\"../../../../../src/runtime/api.js\\"; +import ___CSS_LOADER_ICSS_IMPORT_0___, * as ___CSS_LOADER_ICSS_IMPORT_0____NAMED___ from \\"-!../../../../../src/index.js??[ident]!../../../modules/composes/values.css\\"; +var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(false); +___CSS_LOADER_EXPORT___.i(___CSS_LOADER_ICSS_IMPORT_0___, \\"\\", true); +// Module +___CSS_LOADER_EXPORT___.push([module.id, \\".qwCT06AE1ZDvQtiz0EQJ8 {\\\\n color: \\" + ___CSS_LOADER_ICSS_IMPORT_0____NAMED___[\\"vDef\\"] + \\";\\\\n}\\\\n\\", \\"\\"]); +// Exports +export const vDef = \\"\\" + ___CSS_LOADER_ICSS_IMPORT_0____NAMED___[\\"vDef\\"] + \\"\\"; +export const ghi = \\"qwCT06AE1ZDvQtiz0EQJ8\\"; + +export default ___CSS_LOADER_EXPORT___; +" +`; + +exports[`"esModule" option should work with "exportNamed" option with nested import: result 1`] = ` +Array [ + Array [ + "../../src/index.js?[ident]!./modules/composes/values.css", + " +", + "", + ], + Array [ + "./es-module/named/nested/index.css", + ".qwCT06AE1ZDvQtiz0EQJ8 { + color: red; +} +", + "", + ], +] +`; + +exports[`"esModule" option should work with "exportNamed" option with nested import: warnings 1`] = `Array []`; + +exports[`"esModule" option should work with "exportNamed" option: errors 1`] = `Array []`; + +exports[`"esModule" option should work with "exportNamed" option: module 1`] = ` +"// Imports +import ___CSS_LOADER_API_IMPORT___ from \\"../../../../../src/runtime/api.js\\"; +var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(false); +// Module +___CSS_LOADER_EXPORT___.push([module.id, \\"._1Cb_30DnkF22nebwtzVBFY {\\\\n color: red;\\\\n}\\\\n\\\\n.bar {\\\\n color: red;\\\\n}\\\\n\\", \\"\\"]); +// Exports +export const barBaz = \\"_1Cb_30DnkF22nebwtzVBFY\\"; + +export default ___CSS_LOADER_EXPORT___; +" +`; + +exports[`"esModule" option should work with "exportNamed" option: result 1`] = ` +Array [ + Array [ + "./es-module/named/base/index.css", + "._1Cb_30DnkF22nebwtzVBFY { + color: red; +} + +.bar { + color: red; +} +", + "", + ], +] +`; + +exports[`"esModule" option should work with "exportNamed" option: warnings 1`] = `Array []`; + exports[`"esModule" option should work with a value equal to "false": errors 1`] = `Array []`; exports[`"esModule" option should work with a value equal to "false": module 1`] = ` diff --git a/test/__snapshots__/validate-options.test.js.snap b/test/__snapshots__/validate-options.test.js.snap index b5e12dc9..0719e831 100644 --- a/test/__snapshots__/validate-options.test.js.snap +++ b/test/__snapshots__/validate-options.test.js.snap @@ -6,6 +6,12 @@ exports[`validate options should throw an error on the "esModule" option with "t -> Use the ES modules syntax (https://github.com/webpack-contrib/css-loader#esmodule)." `; +exports[`validate options should throw an error on the "exportNamed" option with "true" value 1`] = ` +"Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. + - options.exportNamed should be a boolean. + -> Use the named export ES modules." +`; + exports[`validate options should throw an error on the "import" option with "true" value 1`] = ` "Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. - options.import should be one of these: @@ -226,49 +232,49 @@ exports[`validate options should throw an error on the "sourceMap" option with " exports[`validate options should throw an error on the "unknown" option with "/test/" value 1`] = ` "Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'unknown'. These properties are valid: - object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }" + object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule?, exportNamed? }" `; exports[`validate options should throw an error on the "unknown" option with "[]" value 1`] = ` "Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'unknown'. These properties are valid: - object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }" + object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule?, exportNamed? }" `; exports[`validate options should throw an error on the "unknown" option with "{"foo":"bar"}" value 1`] = ` "Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'unknown'. These properties are valid: - object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }" + object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule?, exportNamed? }" `; exports[`validate options should throw an error on the "unknown" option with "{}" value 1`] = ` "Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'unknown'. These properties are valid: - object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }" + object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule?, exportNamed? }" `; exports[`validate options should throw an error on the "unknown" option with "1" value 1`] = ` "Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'unknown'. These properties are valid: - object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }" + object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule?, exportNamed? }" `; exports[`validate options should throw an error on the "unknown" option with "false" value 1`] = ` "Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'unknown'. These properties are valid: - object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }" + object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule?, exportNamed? }" `; exports[`validate options should throw an error on the "unknown" option with "test" value 1`] = ` "Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'unknown'. These properties are valid: - object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }" + object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule?, exportNamed? }" `; exports[`validate options should throw an error on the "unknown" option with "true" value 1`] = ` "Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema. - options has an unknown property 'unknown'. These properties are valid: - object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }" + object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule?, exportNamed? }" `; exports[`validate options should throw an error on the "url" option with "true" value 1`] = ` diff --git a/test/esModule-option.test.js b/test/esModule-option.test.js index 3bfdce61..24a5f228 100644 --- a/test/esModule-option.test.js +++ b/test/esModule-option.test.js @@ -100,4 +100,83 @@ describe('"esModule" option', () => { expect(getWarnings(stats)).toMatchSnapshot('warnings'); expect(getErrors(stats)).toMatchSnapshot('errors'); }); + + it('should work with "exportNamed" option', async () => { + const compiler = getCompiler('./es-module/named/base/index.js', { + esModule: true, + modules: true, + exportNamed: true, + }); + const stats = await compile(compiler); + + expect( + getModuleSource('./es-module/named/base/index.css', stats) + ).toMatchSnapshot('module'); + expect(getExecutedCode('main.bundle.js', compiler, stats)).toMatchSnapshot( + 'result' + ); + expect(getWarnings(stats)).toMatchSnapshot('warnings'); + expect(getErrors(stats)).toMatchSnapshot('errors'); + }); + + it('should work with "exportNamed" option with nested import', async () => { + const compiler = getCompiler('./es-module/named/nested/index.js', { + esModule: true, + modules: true, + exportNamed: true, + }); + const stats = await compile(compiler); + + expect( + getModuleSource('./es-module/named/nested/index.css', stats) + ).toMatchSnapshot('module'); + expect(getExecutedCode('main.bundle.js', compiler, stats)).toMatchSnapshot( + 'result' + ); + expect(getWarnings(stats)).toMatchSnapshot('warnings'); + expect(getErrors(stats)).toMatchSnapshot('errors'); + }); + + it('should work js template with "exportNamed" option', async () => { + const compiler = getCompiler('./es-module/named/template/index.js', { + esModule: true, + modules: { + localIdentName: '[local]', + }, + exportNamed: true, + }); + const stats = await compile(compiler); + + expect( + getModuleSource('./es-module/named/template/index.css', stats) + ).toMatchSnapshot('module'); + expect(getExecutedCode('main.bundle.js', compiler, stats)).toMatchSnapshot( + 'result' + ); + expect(getWarnings(stats)).toMatchSnapshot('warnings'); + expect(getErrors(stats)).toMatchSnapshot('errors'); + }); + + it('should emit error when class has unsupported name', async () => { + const compiler = getCompiler('./es-module/named/broken/index.js', { + esModule: true, + modules: true, + exportNamed: true, + }); + const stats = await compile(compiler); + + expect(getWarnings(stats)).toMatchSnapshot('warnings'); + expect(getErrors(stats, true)).toMatchSnapshot('errors'); + }); + + it('should emit error when exportNamed true && esModule false', async () => { + const compiler = getCompiler('./es-module/named/base/index.js', { + esModule: false, + modules: true, + exportNamed: true, + }); + const stats = await compile(compiler); + + expect(getErrors(stats)).toMatchSnapshot('errors'); + }); }); diff --git a/test/fixtures/es-module/named/base/index.css b/test/fixtures/es-module/named/base/index.css new file mode 100644 index 00000000..628f3ed6 --- /dev/null +++ b/test/fixtures/es-module/named/base/index.css @@ -0,0 +1,7 @@ +:local(.bar-baz) { + color: red; +} + +:global(.bar) { + color: red; +} diff --git a/test/fixtures/es-module/named/base/index.js b/test/fixtures/es-module/named/base/index.js new file mode 100644 index 00000000..e1a19303 --- /dev/null +++ b/test/fixtures/es-module/named/base/index.js @@ -0,0 +1,5 @@ +import css from './index.css'; + +__export__ = css; + +export default css; diff --git a/test/fixtures/es-module/named/broken/index.css b/test/fixtures/es-module/named/broken/index.css new file mode 100644 index 00000000..a219fc2f --- /dev/null +++ b/test/fixtures/es-module/named/broken/index.css @@ -0,0 +1,3 @@ +:local(.class) { + color: red; +} diff --git a/test/fixtures/es-module/named/broken/index.js b/test/fixtures/es-module/named/broken/index.js new file mode 100644 index 00000000..e1a19303 --- /dev/null +++ b/test/fixtures/es-module/named/broken/index.js @@ -0,0 +1,5 @@ +import css from './index.css'; + +__export__ = css; + +export default css; diff --git a/test/fixtures/es-module/named/nested/index.css b/test/fixtures/es-module/named/nested/index.css new file mode 100644 index 00000000..ff9669f1 --- /dev/null +++ b/test/fixtures/es-module/named/nested/index.css @@ -0,0 +1,5 @@ +@value v-def from '../../../modules/composes/values.css'; + +.ghi { + color: v-def; +} diff --git a/test/fixtures/es-module/named/nested/index.js b/test/fixtures/es-module/named/nested/index.js new file mode 100644 index 00000000..e1a19303 --- /dev/null +++ b/test/fixtures/es-module/named/nested/index.js @@ -0,0 +1,5 @@ +import css from './index.css'; + +__export__ = css; + +export default css; diff --git a/test/fixtures/es-module/named/template/index.css b/test/fixtures/es-module/named/template/index.css new file mode 100644 index 00000000..b3ccc301 --- /dev/null +++ b/test/fixtures/es-module/named/template/index.css @@ -0,0 +1,11 @@ +:local(.header-baz) { + color: red; +} + +:local(.body) { + color: coral; +} + +:local(.footer) { + color: blue; +} diff --git a/test/fixtures/es-module/named/template/index.js b/test/fixtures/es-module/named/template/index.js new file mode 100644 index 00000000..8dc4c0e0 --- /dev/null +++ b/test/fixtures/es-module/named/template/index.js @@ -0,0 +1,8 @@ +import css from './index.css'; +import html from './template.js'; + +const result = {css, html}; + +__export__ = result; + +export default result; diff --git a/test/fixtures/es-module/named/template/template.js b/test/fixtures/es-module/named/template/template.js new file mode 100644 index 00000000..6bdb73a5 --- /dev/null +++ b/test/fixtures/es-module/named/template/template.js @@ -0,0 +1,11 @@ +import { headerBaz, body, footer } from './index.css'; + +let html = '\n'; + +html += `
\n`; +html += `
\n`; +html += `
\n`; + +__export__ = html; + +export default html; diff --git a/test/validate-options.test.js b/test/validate-options.test.js index 40d5501a..fd115471 100644 --- a/test/validate-options.test.js +++ b/test/validate-options.test.js @@ -71,6 +71,10 @@ describe('validate options', () => { success: [true, false], failure: ['true'], }, + exportNamed: { + success: [true, false], + failure: ['true'], + }, unknown: { success: [], failure: [1, true, false, 'test', /test/, [], {}, { foo: 'bar' }], @@ -92,7 +96,14 @@ describe('validate options', () => { it(`should ${ type === 'success' ? 'successfully validate' : 'throw an error on' } the "${key}" option with "${stringifyValue(value)}" value`, async () => { - const compiler = getCompiler('simple.js', { [key]: value }); + const options = { [key]: value }; + + if (key === 'exportNamed') { + options.esModule = true; + } + + const compiler = getCompiler('simple.js', options); + let stats; try {