Skip to content

Commit

Permalink
fix: Fix ES modules issue.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaywcjlove committed Mar 7, 2022
1 parent 6c85c47 commit a52ab2e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
10 changes: 8 additions & 2 deletions core/src/index.ts
Expand Up @@ -10,7 +10,7 @@ import { overridePaths } from 'kkt/lib/overrides/paths';
import { sync as gzipSize } from 'gzip-size';
import filesize from 'filesize';
import './overrides';
import { filterPlugins, removeLoaders } from './utils';
import { filterPlugins, removeLoaders, hasTypeModule } from './utils';

function help() {
const { version } = require('../package.json');
Expand Down Expand Up @@ -181,6 +181,8 @@ process.on('exit', (code) => {
data.cssFilePath = path.resolve(argvs.out, `${fileName}.css`);
data.cssMinFilePath = path.resolve(argvs.out, `${fileName}.min.css`);

const isESM = inputFile.endsWith('.mjs') || (!inputFile.endsWith('.cjs') && hasTypeModule(inputFile));

if (fs.existsSync(data.fileMinPath)) {
data.fileMin = fs.readFileSync(data.fileMinPath).toString();
}
Expand Down Expand Up @@ -226,14 +228,18 @@ process.on('exit', (code) => {
conf.mode = scriptName === 'watch' ? 'development' : 'production';
conf.output = {};
if (argvs.external) conf.externals = argvs.external;
conf.output.libraryTarget = 'commonjs';
conf.output.libraryTarget = 'commonjs2';
conf.output.path = outDir;
conf.output.filename = data.filename;
if (isWeb) {
conf.output.libraryTarget = 'umd';
if (argvs.library) {
conf.output.library = argvs.library;
}
} else if (isESM) {
conf.output.libraryTarget = 'module';
conf.experiments = conf.experiments ? conf.experiments : {};
conf.experiments.outputModule = true;
}
return conf;
};
Expand Down
14 changes: 14 additions & 0 deletions core/src/utils.ts
@@ -1,3 +1,6 @@
import * as PATH from 'path';
import { readFileSync } from 'fs';
import fs from 'fs-extra';
import { WebpackConfiguration, MiniCssExtractPlugin } from 'kkt';
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
import TerserPlugin from 'terser-webpack-plugin';
Expand Down Expand Up @@ -57,3 +60,14 @@ export function removeLoaders(conf: WebpackConfiguration) {
});
return conf;
}

export function hasTypeModule(path: string) {
while (path !== (path = PATH.resolve(path, '..'))) {
try {
return fs.readJSONSync(PATH.resolve(path, 'package.json')).type === 'module';
} catch (e) {
if (e.code === 'ENOENT') continue;
throw e;
}
}
}

0 comments on commit a52ab2e

Please sign in to comment.