Skip to content

Commit

Permalink
Merge pull request #37 from cezaraugusto/ca/fix-templates2
Browse files Browse the repository at this point in the history
General improvements of all templates
  • Loading branch information
cezaraugusto authored Mar 18, 2024
2 parents 8f4871c + 838cde1 commit e580e87
Show file tree
Hide file tree
Showing 86 changed files with 2,117 additions and 2,993 deletions.
4 changes: 3 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,6 @@ __tests__
**/copyTypesFolder.js
**/copyMarkdownFilesToCli.js
**/copyTailwindConfig.js
**/content.tsx
**/copyStylelintConfig.js
**/content.tsx
**/content.tsx
24 changes: 0 additions & 24 deletions .github/workflows/package-size.yml

This file was deleted.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"clean": "turbo clean && rm -rf node_modules",
"changeset": "changeset",
"compile": "dotenv -- turbo run compile",
"cleanInstall": "yarn cache clean && yarn clean && rm -rf yarn.lock && yarn install && yarn compile && yarn format && yarn lint && yarn tsc --noEmit && yarn test",
"extension": "dotenv -- ts-node ./programs/cli/dist/cli.js",
"format": "prettier --write \"**/*.{ts,tsx,md,js,json}\"",
"lint": "eslint . --config .eslintrc.js",
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
console.log('non-public file')
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
console.log('public file')
8 changes: 5 additions & 3 deletions packages/html-plugin/__tests__/module.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,14 @@ describe('HtmlPlugin (default behavior)', () => {

it('should resolve paths of CSS files for HTML paths defined in MANIFEST.JSON', async () => {
// Handle CSS file that is also a manifest.json features
await findStringInFile(sandboxHtml, '/sandbox/page-0.css')
// Durign development we do not output CSS files and follow wathever style-loader does.
assertFileIsNotEmitted(path.join(outputPath, 'sandbox', 'page-0.css'))
})

it('should resolve paths of CSS files for HTML paths defined in INCLUDE option', async () => {
// Handle CSS file that is also a manifest.json features
await findStringInFile(pagesHtml, '/pages/main.css')
// Handle CSS file that is also a manifest.json features.
// Durign development we do not output CSS files and follow wathever style-loader does.
assertFileIsNotEmitted(path.join(outputPath, 'pages', 'main.css'))
})

it('should resolve paths of CSS files for HTML paths defined in EXCLUDE option', async () => {
Expand Down
27 changes: 19 additions & 8 deletions packages/html-plugin/lib/patchHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ export default function patchHtml(
const htmlFile = fs.readFileSync(htmlEntry, {encoding: 'utf8'})
const htmlDocument = parse5utils.parse(htmlFile)

let hasCssEntry = false
// Ensure that not only we cover files imported by the HTML file
// but also by the JS files imported by the HTML file.
let hasCssEntry = !!compilation.getAsset(feature + '.css')
let hasJsEntry = false

for (let node of htmlDocument.childNodes) {
Expand Down Expand Up @@ -137,15 +139,24 @@ export default function patchHtml(
}

if (htmlChildNode.nodeName === 'head') {
// Create the link tag for the CSS bundle.
// During development this is populated by a mock CSS file
// since we use style-loader to enable HMR for CSS files
// and it inlines the styles into the page.
if (hasCssEntry) {
// Create the link tag for the CSS bundle
const linkTag = parse5utils.createNode('link')
linkTag.attrs = [
{name: 'rel', value: 'stylesheet'},
{name: 'href', value: getFilePath(feature, '.css', true)}
]
// In development mode we use style-loader to enable HMR for CSS files
// and it inlines the styles into the page.
// In production mode we use MiniCssExtractPlugin to extract the CSS
// into a separate file.
if (compilation.options.mode === 'production') {
const linkTag = parse5utils.createNode('link')
linkTag.attrs = [
{name: 'rel', value: 'stylesheet'},
{name: 'href', value: getFilePath(feature, '.css', true)}
]

parse5utils.append(htmlChildNode, linkTag)
parse5utils.append(htmlChildNode, linkTag)
}
}
}

Expand Down
8 changes: 8 additions & 0 deletions packages/html-plugin/minimum-css-file.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* Welcome to tyour CSS file during development!
* To speed up the development process, your styles
* are being injected directly into the head of the document,
* and will be removed when you build your application, along
* with this file. If you are seeing this file in a production build,
* it means that something is wrong with your build configuration.
*/
4 changes: 3 additions & 1 deletion packages/html-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"watch": "yarn compile --watch",
"compile:plugin": "tsup-node ./module.ts ./loaders/InjectHmrAcceptLoader.ts --format cjs --dts --target=node18 --minify",
"compile:web": "tsup-node ./minimum-script-file.ts --format esm --dts --target=node18 --minify --config=tsconfig.web.json",
"compile": "yarn compile:plugin && yarn compile:web",
"compile:css": "copyfiles -f './minimum-css-file.css' dist",
"compile": "yarn compile:plugin && yarn compile:web && yarn compile:css",
"lint": "eslint \"./**/*.ts*\"",
"test": "jest"
},
Expand Down Expand Up @@ -57,6 +58,7 @@
"@types/fs-extra": "^11.0.4",
"@types/jest": "^29.5.12",
"copy-webpack-plugin": "^12.0.2",
"copyfiles": "^2.4.1",
"eslint": "^8.56.0",
"eslint-config-extension-create": "*",
"fs-extra": "^11.2.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export default class AddScriptsAndStylesToCompilation {
)

if (compiler.options.mode === 'development') {
// you can't HMR without a .js file, so we add a minimum script file.
const hmrScript = path.resolve(__dirname, 'minimum-script-file.mjs')
fileAssets.push(hmrScript)
}
Expand Down
8 changes: 4 additions & 4 deletions packages/resources-plugin/src/steps/ApplyCommonFileLoaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ export default class ApplyCommonFileLoaders {
private loaders() {
const getFilename = (runtime: string, folderPath: string) => {
if (runtime.startsWith('content_scripts')) {
const [, filename] = runtime.split('/')
const index = filename.split('-')[1]
const [, contentName] = runtime.split('/')
const index = contentName.split('-')[1]

return `web_accessible_resources/resource-${index}/[name][ext]`
}
Expand All @@ -26,7 +26,7 @@ export default class ApplyCommonFileLoaders {
type: 'asset/resource',
generator: {
filename: ({runtime}: {runtime: string}) =>
getFilename(runtime, 'images')
getFilename(runtime, 'assets')
},
parser: {
dataUrlCondition: {
Expand All @@ -40,7 +40,7 @@ export default class ApplyCommonFileLoaders {
type: 'asset/resource',
generator: {
filename: ({runtime}: {runtime: string}) =>
getFilename(runtime, 'fonts')
getFilename(runtime, 'assets')
}
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ <h1 style="font-size: 4.2em">
created 🔥</h1>
<p id="extensionDescription"></p>
<p>
Designed with practicality and fast prototyping in mind, <a href="https://github.com/cezaraugusto/extension-create">🧩 extension-create</a> is a development tool for browser extensions, allowing developers to create cross-browser extensions with built-in support for TypeScript, auto-reload, and more.
Designed with practicality and fast prototyping in mind, <a target="_blank" href="https://github.com/cezaraugusto/extension-create">🧩 extension-create</a> is a development tool for browser extensions, allowing developers to create cross-browser extensions with built-in support for TypeScript, auto-reload, and more.
</p>
<button id="learnMore">🧩 Learn more about developing cross-browser extensions</button>
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
console.log('background script loaded')
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
console.log('background script (2) loaded')
4 changes: 3 additions & 1 deletion packages/run-chrome-extension/helpers/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ function manifestFieldError(feature: string, htmlFilePath: string) {
feature
)} field in your manifest.json file and try again.`

const errorMessage = `[manifest.json] File path \`${htmlFilePath}\` not found. ${hintMessage}`
const errorMessage = `[manifest.json] File path ${underline(
htmlFilePath
)} not found. ${hintMessage}`
return errorMessage
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ export default function (this: InjectBackgroundAcceptContext, source: string) {
baseDataPath: 'options'
})

if (this._compilation?.options.mode === 'production') return source

const url = urlToRequest(this.resourcePath)

const generalReloadCode = `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,6 @@ class ApplyManifestDevDefaultsPlugin {
(compilation) => {
const Error = compiler.webpack.WebpackError

// This plugin only works during development
if (compiler.options.mode === 'production') return

compilation.hooks.processAssets.tap(
{
name: 'RunChromeExtension (ApplyManifestDevDefaults)',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import fs from 'fs'
import path from 'path'
import type webpack from 'webpack'
import WebExtension from 'webpack-target-webextension'
import {red, bold} from '@colors/colors/safe'
import {type RunChromeExtensionInterface, type Manifest} from '../../../types'
import messages from '../../../helpers/messages'

Expand All @@ -26,7 +27,8 @@ class TargetWebExtensionPlugin {
'background.service_worker',
serviceWorkerPath
)
throw Error(fieldError)
console.error(red(bold(fieldError)))
process.exit(1)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ <h1 style="font-size: 4.2em">
created 🔥</h1>
<p id="extensionDescription"></p>
<p>
Designed with practicality and fast prototyping in mind, <a href="https://github.com/cezaraugusto/extension-create">🧩 extension-create</a> is a development tool for browser extensions, allowing developers to create cross-browser extensions with built-in support for TypeScript, auto-reload, and more.
Designed with practicality and fast prototyping in mind, <a target="_blank" href="https://github.com/cezaraugusto/extension-create">🧩 extension-create</a> is a development tool for browser extensions, allowing developers to create cross-browser extensions with built-in support for TypeScript, auto-reload, and more.
</p>
<button id="learnMore">🧩 Learn more about developing cross-browser extensions</button>
</div>
Expand Down
4 changes: 3 additions & 1 deletion packages/run-edge-extension/helpers/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ function manifestFieldError(feature: string, htmlFilePath: string) {
feature
)} field in your manifest.json file and try again.`

const errorMessage = `[manifest.json] File path \`${htmlFilePath}\` not found. ${hintMessage}`
const errorMessage = `[manifest.json] File path ${underline(
htmlFilePath
)} not found. ${hintMessage}`
return errorMessage
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ export default function (this: InjectBackgroundAcceptContext, source: string) {
baseDataPath: 'options'
})

if (this._compilation?.options.mode === 'production') return source

const url = urlToRequest(this.resourcePath)

const generalReloadCode = `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,6 @@ class ApplyManifestDevDefaultsPlugin {
(compilation) => {
const Error = compiler.webpack.WebpackError

// This plugin only works during development
if (compiler.options.mode === 'production') return

compilation.hooks.processAssets.tap(
{
name: 'RunChromeExtension (ApplyManifestDevDefaults)',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import fs from 'fs'
import path from 'path'
import type webpack from 'webpack'
import WebExtension from 'webpack-target-webextension'
import {red, bold} from '@colors/colors/safe'
import {type RunEdgeExtensionInterface, type Manifest} from '../../../types'
import messages from '../../../helpers/messages'

Expand All @@ -26,7 +27,8 @@ class TargetWebExtensionPlugin {
'background.service_worker',
serviceWorkerPath
)
throw Error(fieldError)
console.error(red(bold(fieldError)))
process.exit(1)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const config = {
},
plugins: [
new ScriptsPlugin({
manifestPath: path.join(__dirname, './manifest.json'),
manifestPath: path.join(__dirname, 'manifest.json'),
include: [path.join(__dirname, 'scripts', 'content-script.js')],
exclude: [
path.join(__dirname, 'public', 'css', 'file.css'),
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@

67 changes: 67 additions & 0 deletions packages/scripts-plugin/helpers/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'path'
import fs from 'fs'
import {type Compiler} from 'webpack'

export function isUsingReact(projectDir: string) {
const packageJsonPath = path.join(projectDir, 'package.json')
Expand All @@ -21,3 +22,69 @@ export function shouldExclude(path: string, ignorePatterns: string[]): boolean {
return path.includes(pattern)
})
}

export function getRelativePath(from: string, to: string) {
let relativePath = path.relative(path.dirname(from), to)
if (!relativePath.startsWith('.') && !relativePath.startsWith('..')) {
relativePath = './' + relativePath
}
return relativePath
}

export function getScriptEntries(
compiler: Compiler,
scriptPath: string | string[] | undefined,
exclude: string[]
): string[] {
const scriptEntries = Array.isArray(scriptPath)
? scriptPath || []
: scriptPath
? [scriptPath]
: []

const fileAssets = scriptEntries.filter((asset) => {
const validFile =
// File exists
fs.existsSync(asset) &&
// Not in some public/ folder
!shouldExclude(asset, exclude)

const validFileExtensions = compiler.options.resolve?.extensions || [
'.js',
'.mjs'
]
const assetExtension = path.extname(asset)

return validFile && validFileExtensions.includes(assetExtension)
})

return fileAssets
}

export function getCssEntries(
scriptPath: string | string[] | undefined,
exclude: string[]
): string[] {
const scriptEntries = Array.isArray(scriptPath)
? scriptPath || []
: scriptPath
? [scriptPath]
: []

const fileAssets = scriptEntries.filter((asset) => {
const validFile =
// File exists
fs.existsSync(asset) &&
// Not in some public/ folder
!shouldExclude(asset, exclude)

return (
(validFile && asset.endsWith('.css')) ||
asset.endsWith('.scss') ||
asset.endsWith('.sass') ||
asset.endsWith('.less')
)
})

return fileAssets
}
Loading

0 comments on commit e580e87

Please sign in to comment.