Skip to content
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

feat: better defaults (0CJS) with config generation #942

Merged
merged 3 commits into from
Jun 8, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 4 additions & 4 deletions bin/utils/prompt-command.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ const runWhenInstalled = (packages, pathForCmd, ...args) => {

module.exports = function promptForInstallation(packages, ...args) {
const nameOfPackage = "@webpack-cli/" + packages;
let packageIsInstalled = false;
let pathForCmd;
try {
let packageIsInstalled = true;
let pathForCmd = "../../packages/init";
/* try {
const path = require("path");
const fs = require("fs");
pathForCmd = path.resolve(process.cwd(), "node_modules", "@webpack-cli", packages);
Expand All @@ -64,7 +64,7 @@ module.exports = function promptForInstallation(packages, ...args) {
packageIsInstalled = true;
} catch (err) {
packageIsInstalled = false;
}
} */
if (!packageIsInstalled) {
const path = require("path");
const fs = require("fs");
Expand Down
68 changes: 42 additions & 26 deletions packages/generators/init-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default class InitGenerator extends Generator {
public constructor(args, opts) {
super(args, opts);

this.usingDefaults = false;
this.usingDefaults = true;
this.autoGenerateConfig = opts.autoSetDefaults ? true : false;

this.dependencies = ["webpack", "webpack-cli", "babel-plugin-syntax-dynamic-import"];
Expand Down Expand Up @@ -122,7 +122,7 @@ export default class InitGenerator extends Generator {
self,
"outputDir",
"In which folder do you want to store your generated bundles?",
"dist",
"'dist'",
this.autoGenerateConfig
);

Expand All @@ -131,13 +131,7 @@ export default class InitGenerator extends Generator {
if (!this.usingDefaults) {
this.configuration.config.webpackOptions.output = {
chunkFilename: "'[name].[chunkhash].js'",
filename: "'[name].[chunkhash].js'",
path: `path.resolve(__dirname, '${outputDir}')`
};
} else {
this.configuration.config.webpackOptions.output = {
filename: "'bundle.js'",
path: `path.resolve(__dirname, '${outputDir}')`
filename: "'[name].[chunkhash].js'"
};
}

Expand All @@ -164,13 +158,13 @@ export default class InitGenerator extends Generator {

({ ExtractUseProps, regExpForStyles } = styleQuestionHandler(self, stylingType));

if (this.isProd) {
if (this.usingDefaults) {
// Ask if the user wants to use extractPlugin
const { useExtractPlugin } = await Input(
self,
"useExtractPlugin",
"If you want to bundle your CSS files, what will you name the bundle? (press enter to skip)",
"null",
"'main.css'",
this.autoGenerateConfig
);

Expand Down Expand Up @@ -205,7 +199,8 @@ export default class InitGenerator extends Generator {
});
}
}
if (!this.isProd) {
if (this.usingDefaults) {
// Html webpack Plugin
this.dependencies.push("html-webpack-plugin");
const htmlWebpackDependency = "html-webpack-plugin";
const htmlwebpackPlugin = generatePluginName(htmlWebpackDependency);
Expand All @@ -214,25 +209,37 @@ export default class InitGenerator extends Generator {
"\n",
tooltip.html()
);
(this.configuration.config.webpackOptions.plugins as string[]).push(`new ${htmlwebpackPlugin}()`);
}
(this.configuration.config.webpackOptions.plugins as string[]).push(`new ${htmlwebpackPlugin}({
template: 'index.html'
})`);

if (!this.usingDefaults) {
// webpack Dev Server
this.dependencies.push("webpack-dev-server");
this.configuration.config.webpackOptions.devServer = {
open: true
};
} else {
this.dependencies.push("terser-webpack-plugin");
this.configuration.config.topScope.push(
tooltip.terser(),
"const TerserPlugin = require('terser-webpack-plugin');",
"\n"
);
}
this.configuration.config.webpackOptions.optimization = getDefaultOptimization(this.usingDefaults);
this.configuration.config.webpackOptions.mode = this.usingDefaults ? "'development'" : "'production'";

// TerserPlugin
this.dependencies.push("terser-webpack-plugin");
this.configuration.config.topScope.push(
tooltip.terser(),
"const TerserPlugin = require('terser-webpack-plugin');",
"\n"
);

// PWA + offline support
this.configuration.config.topScope.push("const workboxPlugin = require('workbox-webpack-plugin');", "\n");
this.dependencies.push("workbox-webpack-plugin");
(this.configuration.config.webpackOptions.plugins as string[]).push(`new workboxPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: false,
})`);

// Chunksplitting
this.configuration.config.webpackOptions.optimization = getDefaultOptimization(this.usingDefaults);
this.configuration.config.webpackOptions.mode = this.usingDefaults ? "'production'" : "'development'";
done();
}

Expand All @@ -250,15 +257,15 @@ export default class InitGenerator extends Generator {
this.config.set("configuration", this.configuration);

const packageJsonTemplatePath = "./templates/package.json.js";
this.fs.extendJSON(this.destinationPath("package.json"), require(packageJsonTemplatePath)(this.isProd));
this.fs.extendJSON(this.destinationPath("package.json"), require(packageJsonTemplatePath)(this.usingDefaults));

const generateEntryFile = (entryPath: string, name: string): void => {
entryPath = entryPath.replace(/'/g, "");
this.fs.copyTpl(path.resolve(__dirname, "./templates/index.js"), this.destinationPath(entryPath), { name });
};

// Generate entry file/files
const entry = this.configuration.config.webpackOptions.entry;
const entry = this.configuration.config.webpackOptions.entry || "./src/index.js";
if (typeof entry === "string") {
generateEntryFile(entry, "your main file!");
} else if (typeof entry === "object") {
Expand All @@ -268,6 +275,15 @@ export default class InitGenerator extends Generator {
// Generate README
this.fs.copyTpl(path.resolve(__dirname, "./templates/README.md"), this.destinationPath("README.md"), {});

// Generate HTML template file
if (this.usingDefaults) {
this.fs.copyTpl(
path.resolve(__dirname, "./templates/template.html"),
this.destinationPath("index.html"),
{}
);
}

// Genrate tsconfig
if (this.langType === LangType.Typescript) {
const tsConfigTemplatePath = "./templates/tsconfig.json.js";
Expand Down
4 changes: 2 additions & 2 deletions packages/generators/templates/package.json.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module.exports = isProd => {
module.exports = usingDefaults => {
let scripts = {
build: "webpack"
};
if (!isProd) {
if (usingDefaults) {
scripts.start = "webpack-dev-server";
}

Expand Down
25 changes: 25 additions & 0 deletions packages/generators/templates/template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Webpack App</title>
</head>
<body>
<h1>Hello world!</h1>
<h2>Tip: Check your console</h2>
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker
.register("/sw.js")
.then(registration => {
console.log("SW registered: ", registration);
})
.catch(registrationError => {
console.log("SW registration failed: ", registrationError);
});
});
}
</script>
</body>
</html>
5 changes: 3 additions & 2 deletions packages/generators/utils/webpackConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { WebpackOptions } from "../types";

export function getDefaultOptimization(usingDefaults: boolean): WebpackOptions["optimization"] {
let optimizationOptions;
if (usingDefaults) {
if (!usingDefaults) {
optimizationOptions = {
minimizer: ["new TerserPlugin()"],
splitChunks: {
cacheGroups: {
vendors: {
Expand All @@ -14,7 +15,7 @@ export function getDefaultOptimization(usingDefaults: boolean): WebpackOptions["
chunks: "'async'",
minChunks: 1,
minSize: 30000,
name: !this.isProd
name: !usingDefaults
}
};
} else {
Expand Down
4 changes: 2 additions & 2 deletions packages/utils/scaffold.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ export default function runTransform(transformConfig: TransformConfig, action: s
}
);

const runCommand = getPackageManager() === "yarn" ? "yarn start" : "npm run start";
const runCommand = getPackageManager() === "yarn" ? "yarn build" : "npm run build";

let successMessage: string =
chalk.green(`Congratulations! Your new webpack configuration file has been created!\n\n`) +
`You can now run ${chalk.green(runCommand)} to run your project!\n\n`;
`You can now run ${chalk.green(runCommand)} to bundle your application!\n\n`;

if (initActionNotDefined && transformConfig.config.item) {
successMessage = chalk.green(`Congratulations! ${transformConfig.config.item} has been ${action}ed!\n`);
Expand Down