Skip to content

Commit

Permalink
feat: rework package to use .mjs files and all scripts and styles are…
Browse files Browse the repository at this point in the history
… minified
  • Loading branch information
nolimits4web committed Jun 23, 2023
1 parent 3789a9d commit a267785
Show file tree
Hide file tree
Showing 140 changed files with 435 additions and 416 deletions.
92 changes: 48 additions & 44 deletions scripts/build-modules.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,33 @@ export default async function buildModules() {
const modules = [];
configModules.forEach((name) => {
const capitalized = capitalizeString(name);
const jsFilePath = `./src/modules/${name}/${name}.js`;
const jsFilePath = `./src/modules/${name}/${name}.mjs`;
if (fs.existsSync(jsFilePath)) {
modules.push({ name, capitalized });
}
});

// eslint-disable-next-line
const modulesPaths = configModules.map((name) => {
return `./src/modules/${name}/${name}.js`;
return `./src/modules/${name}/${name}.mjs`;
});

const output = await rollup({
external: ['react', 'vue'],
input: [
'./src/swiper.js',
'./src/swiper-bundle.js',
'./src/swiper-element.js',
'./src/swiper-element-bundle.js',
'./src/swiper-vue.js',
'./src/swiper-react.js',
'./src/swiper.mjs',
'./src/swiper-bundle.mjs',
'./src/swiper-element.mjs',
'./src/swiper-element-bundle.mjs',
'./src/swiper-vue.mjs',
'./src/swiper-react.mjs',
...modulesPaths,
],
plugins: [
replace({
delimiters: ['', ''],
'//IMPORT_MODULES': modules
.map((mod) => `import ${mod.capitalized} from './modules/${mod.name}/${mod.name}.js';`)
.map((mod) => `import ${mod.capitalized} from './modules/${mod.name}/${mod.name}.mjs';`)
.join('\n'),
'//INSTALL_MODULES': modules.map((mod) => `${mod.capitalized}`).join(',\n '),
'//EXPORT': 'export default Swiper; export { Swiper }',
Expand All @@ -54,10 +54,11 @@ export default async function buildModules() {
await output.write({
dir: `./dist/tmp`,
format: 'esm',
entryFileNames: '[name].mjs',
hoistTransitiveImports: false,
chunkFileNames: (i) => {
if (i.name === 'swiper') return `swiper-core.js`;
return `[name].js`;
if (i.name === 'swiper') return `swiper-core.mjs`;
return `[name].mjs`;
},
});

Expand All @@ -67,24 +68,21 @@ export default async function buildModules() {
fs.mkdirSync(`./dist/modules`);
}
files.forEach((fileName) => {
const folderName = fileName.split('.js')[0];
const folderName = fileName.split('.mjs')[0];
if (fs.existsSync(`./src/modules/${folderName}`)) {
if (!fs.existsSync(`./dist/modules/${folderName}`)) {
fs.mkdirSync(`./dist/modules/${folderName}`);
}
fs.copyFileSync(`./dist/tmp/${fileName}`, `./dist/modules/${folderName}/${fileName}`);
fs.copyFileSync(`./dist/tmp/${fileName}`, `./dist/modules/${fileName}`);
fs.unlinkSync(`./dist/tmp/${fileName}`);
} else if (
(fileName.indexOf('swiper-') !== 0 && fileName !== 'swiper.js') ||
fileName === 'swiper-core.js'
(fileName.indexOf('swiper-') !== 0 && fileName !== 'swiper.mjs') ||
fileName === 'swiper-core.mjs'
) {
if (!fs.existsSync('./dist/shared')) {
fs.mkdirSync('./dist/shared');
}
fs.copyFileSync(`./dist/tmp/${fileName}`, `./dist/shared/${fileName}`);
fs.unlinkSync(`./dist/tmp/${fileName}`);
} else {
fs.copyFileSync(`./dist/tmp/${fileName}`, `./dist/${fileName.replace('.js', '.mjs')}`);
fs.copyFileSync(`./dist/tmp/${fileName}`, `./dist/${fileName}`);
fs.unlinkSync(`./dist/tmp/${fileName}`);
}
});
Expand All @@ -93,12 +91,14 @@ export default async function buildModules() {
}

// FIX IMPORTS
fs.readdirSync('./dist/modules').forEach((modName) => {
const content = fs
.readFileSync(`./dist/modules/${modName}/${modName}.js`, 'utf-8')
.replace(/from '\.\//g, `from '../../shared/`);
fs.writeFileSync(`./dist/modules/${modName}/${modName}.js`, content);
});
fs.readdirSync('./dist/modules')
.filter((f) => f.includes('.mjs'))
.forEach((modName) => {
const content = fs
.readFileSync(`./dist/modules/${modName}`, 'utf-8')
.replace(/from '\.\//g, `from '../shared/`);
fs.writeFileSync(`./dist/modules/${modName}`, content);
});

const { core, bundle, slide } = await getElementStyles();

Expand All @@ -110,8 +110,8 @@ export default async function buildModules() {
content = content
.replace(/from '\.\/swiper-core/g, `from './shared/swiper-core`)
.replace(
/import ([0-9A-Za-z]*) from '\.\/([0-9a-z-]*).js'/g,
`import $1 from './modules/$2/$2.js'`,
/import ([0-9A-Za-z]*) from '\.\/([0-9a-z-]*).mjs'/g,
`import $1 from './modules/$2.mjs'`,
);
} else {
content = content.replace(/from '\.\//g, `from './shared/`);
Expand Down Expand Up @@ -140,25 +140,30 @@ export default async function buildModules() {
fs.writeFileSync(`./dist/${f}`, `${banner(bannerName)}\n${content}`);
});

// MODULES_INDEX
fs.writeFileSync(
'./dist/modules/index.mjs',
modules
.map((mod) => `export {default as ${mod.capitalized}} from './${mod.name}.mjs';`)
.join('\n'),
);

// MINIFY
await Promise.all([
// MINIFY SHARED
...fs
.readdirSync('./dist/shared')
.filter((f) => f.endsWith('.js') && !f.includes('.min'))
.map((f) => minify(f, `./dist/shared/${f}`, true)),
.filter((f) => f.endsWith('.mjs'))
.map((f) => minify(f, `./dist/shared/${f}`)),
// MINIFY MODULES
...fs
.readdirSync('./dist/modules')
.filter((f) => f.endsWith('.js') && !f.includes('.min'))
.map((f) => minify(f, `./dist/modules/${f}/${f}.js`, true)),
.filter((f) => f.endsWith('.mjs'))
.map((f) => minify(f, `./dist/modules/${f}`)),
// MINIFY ROOT
...fs
.readdirSync('./dist/')
.filter(
(f) =>
f.endsWith('.mjs') && !f.includes('.min') && !f.includes('react') && !f.includes('vue'),
)
.filter((f) => f.endsWith('.mjs') && !f.includes('react') && !f.includes('vue'))
.map((f) => {
const bannerName = f.includes('react')
? 'React'
Expand All @@ -167,21 +172,20 @@ export default async function buildModules() {
: f.includes('element')
? 'Custom Element'
: '';
return minify(f, `./dist/${f}`, false, bannerName);
return minify(f, `./dist/${f}`, bannerName);
}),
]);

// IIFE
const replaceExports = {};
['swiper-bundle.mjs', 'swiper.mjs'].forEach((f) => {
const content = fs.readFileSync(`./dist/${f}`, 'utf-8');
const line = content
.split('\n')
.filter((l) => l.includes('export {'))[0]
.trim();
const before = content.match(/export{([^,]*),([^}]*)}/)[0];
const after = before.replace(/export{([^,]*),([^}]*)}/, `export {$2}`);

replaceExports[f] = {
before: line,
after: line.replace(/export { ([^,]*), ([^}]*) }/, `export { $2 }`),
before,
after,
};
fs.writeFileSync(
`./dist/${f}`,
Expand All @@ -198,7 +202,7 @@ export default async function buildModules() {
replace({
preventAssignment: true,
delimiters: ['', ''],
'export { SwiperContainer, SwiperSlide, register };': 'register()',
'export{SwiperContainer,SwiperSlide,register};': 'register();',
}),
],
});
Expand All @@ -224,7 +228,7 @@ export default async function buildModules() {
await Promise.all(
['swiper-bundle.js', 'swiper.js', 'swiper-element.js', 'swiper-element-bundle.js'].map((f) => {
const bannerName = f.includes('element') ? 'Custom Element' : '';
return minify(f, `./dist/${f}`, false, bannerName);
return minify(f, `./dist/${f}`, bannerName);
}),
);
}
18 changes: 10 additions & 8 deletions scripts/build-styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,7 @@ const buildCSS = async ({ isBundle, modules, minified }) => {
let lessContent = await fs.readFile(path.resolve(__dirname, '../src/swiper.less'), 'utf8');
lessContent = lessContent.replace(
'//IMPORT_MODULES',
!isBundle
? ''
: modules.map((mod) => `@import url('./modules/${mod}/${mod}.less');`).join('\n'),
!isBundle ? '' : modules.map((mod) => `@import url('./modules/${mod}.less');`).join('\n'),
);
const cssContent = await autoprefixer(
await less(lessContent, path.resolve(__dirname, '../src')),
Expand All @@ -62,14 +60,14 @@ const buildCSS = async ({ isBundle, modules, minified }) => {

if (minified) {
const minifiedContent = await minifyCSS(cssContent);
await fs.writeFile(`./${outputDir}/${fileName}.min.css`, `${banner()}\n${minifiedContent}`);
await fs.writeFile(`./${outputDir}/${fileName}.css`, `${banner()}\n${minifiedContent}`);
}
};
export default async function buildStyles() {
elapsed.start('styles');
// eslint-disable-next-line import/no-named-as-default-member
const modules = config.modules.filter((name) => {
const lessFilePath = `./src/modules/${name}/${name}.less`;
const lessFilePath = `./src/modules/${name}.less`;
return fs.existsSync(lessFilePath);
});
buildCSS({ isBundle: true, modules, minified: isProd });
Expand All @@ -84,12 +82,16 @@ export default async function buildStyles() {
);
await Promise.all(
files.map(async (file) => {
const distFilePath = path.resolve(__dirname, `../${outputDir}`, file);
let distFilePath = path.resolve(__dirname, `../${outputDir}`, file);
const srcFilePath = path.resolve(__dirname, '../src', file);
let distFileContent = await readSwiperFile(srcFilePath);
distFileContent = distFileContent.replace('../../swiper-vars', '../swiper-vars');
if (file === 'swiper.scss' || file === 'swiper.less') {
distFileContent = `${banner()}\n${distFileContent}`;
}
if (distFilePath.includes('/modules/')) {
distFilePath = distFilePath.replace(/modules\/([a-zA-Z0-9-]*)/, 'modules');
}
await fs.ensureDir(path.dirname(distFilePath));
await fs.writeFile(distFilePath, distFileContent);
}),
Expand All @@ -110,8 +112,8 @@ export default async function buildStyles() {
const resultFilePath = filePath.replace(/\.less$/, '');
const minifiedCSS = await minifyCSS(resultCSS);
const minifiedCSSElement = await minifyCSS(resultCSSElement);
await fs.writeFile(`${resultFilePath}.min.css`, minifiedCSS);
await fs.writeFile(`${resultFilePath}-element.min.css`, minifiedCSSElement);
await fs.writeFile(`${resultFilePath}.css`, minifiedCSS);
await fs.writeFile(`${resultFilePath}-element.css`, minifiedCSSElement);
}),
);
}
Expand Down
2 changes: 1 addition & 1 deletion scripts/build-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export default async function buildTypes() {
const eventsFiles = await globby('src/types/modules/*.d.ts');
await Promise.all(
eventsFiles.map(async (eventsFile) => {
if (eventsFile.indexOf('public-api') > -1) {
if (eventsFile.indexOf('public-api') > -1 || eventsFile.indexOf('index') > -1) {
return;
}
let eventsContent = await fs.readFile(eventsFile, 'utf-8');
Expand Down
16 changes: 7 additions & 9 deletions scripts/utils/minify.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ import { minify } from 'terser';
import fs from 'fs';
import { banner } from './banner.js';

export default async (fileName, filePath, inPlace, bannerName) => {
export default async (fileName, filePath, bannerName, sourceMap) => {
const content = fs.readFileSync(filePath, 'utf-8');
const fileExt = fileName.includes('.mjs') ? '.mjs' : '.js';
const { code, map } = await minify(content, {
...(inPlace
...(!sourceMap
? {}
: {
sourceMap: {
filename: `${fileName}.min${fileExt}`,
url: `${fileName}.min${fileExt}.map`,
filename: `${fileName}.mjs`,
url: `${fileName}.mjs.map`,
},
}),

Expand All @@ -21,10 +21,8 @@ export default async (fileName, filePath, inPlace, bannerName) => {
}).catch((err) => {
console.error(`Terser failed on file ${fileName}: ${err.toString()}`);
});
if (inPlace) {
fs.writeFileSync(filePath, code);
} else {
fs.writeFileSync(filePath.replace(`${fileExt}`, `.min${fileExt}`), code);
fs.writeFileSync(filePath.replace(`${fileExt}`, `.min${fileExt}.map`), map);
fs.writeFileSync(filePath, code);
if (sourceMap) {
fs.writeFileSync(filePath.replace(`${fileExt}`, `.mjs.map`), map);
}
};
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { paramsList } from './params-list.js';
import { isObject } from './utils.js';
import { paramsList } from './params-list.mjs';
import { isObject } from './utils.mjs';

function getChangedParams(swiperParams, oldParams, children, oldChildren, getKey) {
const keys = [];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Swiper } from '../swiper.js';
import { isObject, extend } from './utils.js';
import { paramsList } from './params-list.js';
import { Swiper } from '../swiper.mjs';
import { isObject, extend } from './utils.mjs';
import { paramsList } from './params-list.mjs';

function getParams(obj = {}, splitEvents = true) {
const params = {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { needsNavigation, needsPagination, needsScrollbar } from './utils.js';
import { needsNavigation, needsPagination, needsScrollbar } from './utils.mjs';

function mountSwiper({ el, nextEl, prevEl, paginationEl, scrollbarEl, swiper }, swiperParams) {
if (needsNavigation(swiperParams) && nextEl && prevEl) {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isObject, extend } from './utils.js';
import { isObject, extend } from './utils.mjs';

function updateSwiper({
swiper,
Expand Down
File renamed without changes.
Loading

0 comments on commit a267785

Please sign in to comment.