Skip to content

Commit

Permalink
Migrate to ESM
Browse files Browse the repository at this point in the history
  • Loading branch information
yoriiis committed Jun 27, 2023
1 parent d0a41da commit 8118a49
Show file tree
Hide file tree
Showing 17 changed files with 91 additions and 49 deletions.
26 changes: 13 additions & 13 deletions README.md
Expand Up @@ -32,9 +32,9 @@ npm install svg-chunk-webpack-plugin --save-dev
yarn add svg-chunk-webpack-plugin --dev
```

## Environment

`svg-chunk-webpack-plugin` was built for Node.js `>=16.20.0` and Webpack `>=5.10.3`.
> **Warning** `svg-chunk-webpack-plugin@5` is ESM only.
>
> **Note** Minimum supported `Node.js` version is `16.20.0` and Webpack `>=5.10.3`.
## Example

Expand All @@ -51,9 +51,9 @@ First, let's add the loader and the plugin to the Webpack configuration.
**webpack.config.js**

```javascript
const SvgChunkWebpackPlugin = require('svg-chunk-webpack-plugin');
import SvgChunkWebpackPlugin from 'svg-chunk-webpack-plugin';

module.exports = {
export default {
module: {
rules: [
{
Expand Down Expand Up @@ -117,7 +117,7 @@ Tells the loader whether to load the custom [SVGO configuration](https://github.
**webpack.config.js**

```js
module.exports = {
export default {
module: {
rules: [
{
Expand All @@ -139,7 +139,7 @@ SVGO have a default preset to optimize SVG files. See [how to configure svgo](ht
**svgo.config.js**

```js
module.exports = {
export default {
multipass: true,
plugins: [
{
Expand Down Expand Up @@ -179,7 +179,7 @@ Tells the plugin whether to personalize the default sprite filename. The placeho
**webpack.config.js**

```javascript
module.exports = {
export default {
plugins: [
new SvgChunkWebpackPlugin({
filename: '[name].svg'
Expand All @@ -205,7 +205,7 @@ SVG sprites are built using the `svgstore` package. Update the parameters accord
**webpack.config.js**

```javascript
module.exports = {
export default {
plugins: [
new SvgChunkWebpackPlugin({
svgstoreConfig: {
Expand Down Expand Up @@ -236,7 +236,7 @@ Tells the plugin whether to generate the `sprites-manifest.json`. The JSON file
**webpack.config.js**

```javascript
module.exports = {
export default {
plugins: [
new SvgChunkWebpackPlugin({
generateSpritesManifest: true
Expand All @@ -260,7 +260,7 @@ Tells the plugin whether to generate the `sprites-preview.html`. The HTML previe
**webpack.config.js**

```javascript
module.exports = {
export default {
plugins: [
new SvgChunkWebpackPlugin({
generateSpritesPreview: true
Expand All @@ -286,7 +286,7 @@ The `[contenthash]` placeholder will add a unique hash based on the content of t
**webpack.config.js**

```javascript
module.exports = {
export default {
plugins: [
new SvgChunkWebpackPlugin({
filename: '[name].[contenthash].svg'
Expand All @@ -302,7 +302,7 @@ The `[fullhash]` placeholder will add a unique hash generated for every build. W
**webpack.config.js**

```javascript
module.exports = {
export default {
plugins: [
new SvgChunkWebpackPlugin({
filename: '[name].[fullhash].svg'
Expand Down
File renamed without changes.
13 changes: 11 additions & 2 deletions config/jest.config.js
@@ -1,14 +1,23 @@
module.exports = {
export default {
moduleFileExtensions: ['js', 'ts'],
modulePaths: ['<rootDir>/src'],
resetModules: true,
rootDir: '../',
transform: {
'\\.(js|ts)$': 'ts-jest'
'\\.(js|ts)$': [
'ts-jest',
{
diagnostics: {
// Disable error reporting with import assertions
ignoreCodes: ['TS1343', 'TS2821']
}
}
]
},
moduleNameMapper: {
'^@src(.*)$': '<rootDir>/src$1'
},
resolver: 'jest-ts-webcompat-resolver', // Used to fix .js resolution in .ts files
testMatch: ['<rootDir>/tests/*.test.js'],
verbose: true,
resetMocks: true
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion example/dist/js/news.js

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

2 changes: 1 addition & 1 deletion example/src/js/home.js
@@ -1,4 +1,4 @@
import '../svgs/gradient.svg';
import '../svgs/video.svg';

import './component';
import './component.js';
2 changes: 1 addition & 1 deletion example/svgo.config.js
@@ -1,4 +1,4 @@
module.exports = {
export default {
multipass: true,
plugins: [
{
Expand Down
14 changes: 9 additions & 5 deletions example/webpack.config.js
@@ -1,9 +1,13 @@
const path = require('path');
const TerserJSPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const SvgChunkWebpackPlugin = require('../lib/index.js');
import path from 'path';
import { fileURLToPath } from 'url';
import TerserJSPlugin from 'terser-webpack-plugin';
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
import SvgChunkWebpackPlugin from '../lib/index.js';

module.exports = (env, argv) => {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default (env, argv) => {
const isProduction = argv.mode === 'production';

return {
Expand Down
14 changes: 12 additions & 2 deletions package-lock.json

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

11 changes: 6 additions & 5 deletions package.json
@@ -1,6 +1,6 @@
{
"name": "svg-chunk-webpack-plugin",
"version": "4.0.2",
"version": "5.0.0",
"description": "Generate SVG sprites according to entrypoint dependencies. Each page only imports its own svgs, wrapped as a sprite and optimized by svgo",
"keywords": [
"svg",
Expand All @@ -24,7 +24,8 @@
},
"license": "MIT",
"author": "Joris DANIEL",
"main": "./lib/index.js",
"type": "module",
"exports": "./lib/index.js",
"types": "./types/index.d.ts",
"files": [
"lib",
Expand All @@ -33,19 +34,18 @@
"scripts": {
"build": "rm -rf ./types ./lib && tsc",
"build:example": "rm -rf ./example/dist/ && webpack --config=./example/webpack.config.js --mode=production",
"coverage": "jest --coverage && cat ./coverage/lcov.info | coveralls",
"dev": "tsc --watch",
"dev:unit": "jest --config ./config/jest.config.js --verbose --coverage --watch",
"inspect:example": "rm -rf ./example/dist/ && node --inspect node_modules/webpack/bin/webpack.js --config=./example/webpack.config.js --mode=development",
"pre:publish": "npm run build && npm run build:example && npm run test",
"start:example": "rm -rf ./example/dist/ && webpack --config=./example/webpack.config.js --mode=development",
"test": "npm run test:eslint && npm run test:types && npm run test:markdown && npm run test:unit",
"test:eslint": "eslint . -c ./config/.eslintrc.js --ignore-pattern coverage --ignore-pattern reports --ignore-pattern example/dist --ignore-pattern lib --ignore-pattern types",
"test:eslint": "eslint . -c ./config/.eslintrc.cjs --ignore-pattern coverage --ignore-pattern reports --ignore-pattern example/dist --ignore-pattern lib --ignore-pattern types",
"test:markdown": "markdownlint \"**/*.md\" --ignore node_modules",
"test:types": "tsc --noEmit",
"test:unit": "jest --config ./config/jest.config.js --verbose --coverage"
},
"prettier": "./config/prettier.config.js",
"prettier": "./config/prettier.config.cjs",
"dependencies": {
"extend": "^3.0.2",
"schema-utils": "^4.0.1",
Expand Down Expand Up @@ -73,6 +73,7 @@
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-promise": "^6.1.1",
"jest": "^29.5.0",
"jest-ts-webcompat-resolver": "^1.0.0",
"markdownlint-cli": "^0.33.0",
"mini-css-extract-plugin": "^2.7.5",
"prettier": "^2.8.7",
Expand Down
14 changes: 7 additions & 7 deletions src/index.ts
Expand Up @@ -3,10 +3,10 @@ import path from 'path';
import { validate } from 'schema-utils';
import svgstore from 'svgstore';
import extend from 'extend';
import templatePreview from './preview';
import unTypedSchemaOptions from './schemas/plugin-options.json';
import templatePreview from './preview.js';
import unTypedSchemaOptions from './schemas/plugin-options.json' assert { type: 'json' };
import type { Compiler, Compilation, NormalModule, Chunk, Module, sources } from 'webpack';
import { Schema } from 'schema-utils/declarations/validate';
import { Schema } from 'schema-utils/declarations/validate.js';
import {
Svgs,
SpriteManifest,
Expand All @@ -15,9 +15,9 @@ import {
SvgsData,
PluginOptions,
SvgstoreConfig
} from './types';
} from './types.js';
import { PACKAGE_NAME, esmResolve } from './utils.js';

const PACKAGE_NAME = require('../package.json').name;
const schemaOptions = unTypedSchemaOptions as Schema;

/**
Expand Down Expand Up @@ -408,6 +408,6 @@ class SvgChunkWebpackPlugin {
}

// @ts-ignore
SvgChunkWebpackPlugin.loader = require.resolve('./loader');
SvgChunkWebpackPlugin.loader = esmResolve('./loader.js');

export = SvgChunkWebpackPlugin;
export default SvgChunkWebpackPlugin;
15 changes: 9 additions & 6 deletions src/loader.ts
@@ -1,18 +1,21 @@
import { optimize, loadConfig } from 'svgo';
import { validate } from 'schema-utils';
import unTypedSchemaOptions from './schemas/loader-options.json';
import { Schema } from 'schema-utils/declarations/validate';
import { LoaderThis, LoaderOptions } from './types';
import unTypedSchemaOptions from './schemas/loader-options.json' assert { type: 'json' };
import { Schema } from 'schema-utils/declarations/validate.js';
import { LoaderThis, LoaderOptions } from './types.js';
import { PACKAGE_NAME } from './utils.js';

const PACKAGE_NAME = require('../package.json').name;
const schemaOptions = unTypedSchemaOptions as Schema;

/**
* Loader for SVG files
* Content are not edited, just stringified
* The plugin create sprites
*/
export = async function SvgChunkWebpackLoader(this: LoaderThis, content: string): Promise<string> {
export default async function SvgChunkWebpackLoader(
this: LoaderThis,
content: string
): Promise<string> {
const options: LoaderOptions = this.getOptions() || {};

validate(schemaOptions, options, {
Expand Down Expand Up @@ -62,4 +65,4 @@ export = async function SvgChunkWebpackLoader(this: LoaderThis, content: string)
} catch (error) {
return callback(error);
}
};
}
6 changes: 3 additions & 3 deletions src/preview.ts
@@ -1,6 +1,6 @@
import { Sprite } from './types';
import { Sprite } from './types.js';

export = function templatePreview(sprites: Sprite[]): string {
export default function templatePreview(sprites: Sprite[]): string {
/* prettier-ignore */
return `<!DOCTYPE html>
<html lang="en">
Expand Down Expand Up @@ -71,4 +71,4 @@ export = function templatePreview(sprites: Sprite[]): string {
`).join('')}
</body>
</html>`;
};
}
7 changes: 7 additions & 0 deletions src/utils.ts
@@ -0,0 +1,7 @@
import path from 'path';
import { fileURLToPath } from 'url';

export const PACKAGE_NAME = 'svg-chunk-webpack-plugin' as const;

export const esmResolve = (filePath: string) =>
path.resolve(path.dirname(fileURLToPath(import.meta.url)), filePath);
4 changes: 4 additions & 0 deletions tests/index.test.js
Expand Up @@ -6,6 +6,10 @@ import schemaOptions from '@src/schemas/plugin-options.json';

jest.mock('@src/preview');
jest.mock('schema-utils');
jest.mock('@src/utils', () => ({
PACKAGE_NAME: 'svg-chunk-webpack-plugin',
esmResolve: jest.fn()
}));
jest.mock('webpack', () => {
return {
Compilation: {
Expand Down
6 changes: 5 additions & 1 deletion tests/loader.test.js
Expand Up @@ -5,9 +5,13 @@ import svgoConfig from '../example/svgo.config';
import { optimize, loadConfig } from 'svgo';
import { validate } from 'schema-utils';
import schemaOptions from '@src/schemas/loader-options.json';
const PACKAGE_NAME = require('../package.json').name;
import { PACKAGE_NAME } from '@src/utils';

jest.mock('schema-utils');
jest.mock('@src/utils', () => ({
PACKAGE_NAME: 'svg-chunk-webpack-plugin',
esmResolve: jest.fn()
}));
jest.mock('svgo', () => {
const originalModule = jest.requireActual('svgo');
return {
Expand Down
4 changes: 2 additions & 2 deletions tsconfig.json
@@ -1,8 +1,8 @@
{
"compilerOptions": {
"strict": true,
"module": "commonjs",
"moduleResolution": "node",
"module": "nodenext",
"moduleResolution": "node16",
"target": "esnext",
"lib": ["ESNext"],
"outDir": "./lib",
Expand Down

0 comments on commit 8118a49

Please sign in to comment.