Skip to content

(feat) copy package.json functionality, update migration script #9115

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

Closed
wants to merge 4 commits into from
Closed
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
5 changes: 5 additions & 0 deletions .changeset/odd-dragons-complain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/package': minor
---

feat: add copy package.json functionality
5 changes: 5 additions & 0 deletions .changeset/smart-actors-play.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte-migrate': patch
---

fix: use copy-package.json-functionality to fully resemble old way of doing things
7 changes: 7 additions & 0 deletions documentation/docs/30-advanced/70-packaging.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ declare module 'your-library/Foo.svelte';
import Foo from 'your-library/Foo.svelte';
```

> Note that TypeScript will not recognize typings of deep imports by default. You have two options to solve this:
> - require people to set their `moduleResolution` `tsconfig.json` option to `bundler` (probably the best option for most apps but only available since TypeScript version 5), `node16` or `nodenext`. This is the more future proof option
> - use the [`--copy` option](#options). This will move your `package.json` and other relevant top level files into the output folder so that you can publish your library from there. This means you should author your `exports` map and `svelte` field in your `package.json` not relative to the root of your project but relative to the output folder. If `publint` is part of your `package` script, also update its command to `publint run <output folder>`.

In general, each key of the exports map is the path the user will have to use to import something from your package, and the value is the path to the file that will be imported or a map of export conditions which in turn contains these file paths.

Read more about `exports` [here](https://nodejs.org/docs/latest-v18.x/api/packages.html#package-entry-points).
Expand Down Expand Up @@ -165,6 +169,7 @@ You should think carefully about whether or not the changes you make to your pac
- `-i`/`--input` — the input directory which contains all the files of the package. Defaults to `src/lib`
- `-o`/`--o` — the output directory where the processed files are written to. You `package.json`'s `exports` should point to files inside there, and the `files` array should include that folder. Defaults to `dist`
- `-t`/`--types` — whether or not to create type definitions (`d.ts` files). We strongly recommend doing this as it fosters ecosystem library quality. Defaults to `true`
- `-c`/`--copy` — if set, will copy over the `package.json`, `.npmignore`, `license.md` and `readme.md` into the output folder. This is benefitial if you have more than one entry point and want people to be able to consume your package with correct types without them having to set the `moduleResolution` `tsconfig.json` option to `node16`, `nodenext` or `bundler`. You would then run `npm publish` from within your output folder, not from the root. This means you should author your `exports` map and `svelte` field in your `package.json` not relative to the root of your project but relative to the output folder. If `publint` is part of your `package` script, also update its command to `publint run <output folder>`.

## Publishing

Expand All @@ -174,6 +179,8 @@ To publish the generated package:
npm publish
```

If you're using the [`--copy` option](#options), `cd` into the output directory first.

## Caveats

All relative file imports need to be fully specified, adhering to Node's ESM algorithm. This means that for a file like `src/lib/something/index.js`, you must include the filename with the extension:
Expand Down
15 changes: 5 additions & 10 deletions packages/migrate/migrations/package/migrate_pkg.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export function update_pkg_json(config, pkg, files) {
for (const key in pkg.scripts || []) {
const script = pkg.scripts[key];
if (script.includes('svelte-package')) {
pkg.scripts[key] = script.replace('svelte-package', `svelte-package -o ${out_dir}`);
pkg.scripts[key] = script.replace('svelte-package', `svelte-package -o ${out_dir} -c`);
}
}

Expand All @@ -81,13 +81,8 @@ export function update_pkg_json(config, pkg, files) {
...pkg.exports
};

pkg.files = pkg.files || [];
if (!pkg.files.includes(out_dir)) {
pkg.files.push(out_dir);
}

if (pkg.devDependencies?.['@sveltejs/package']) {
pkg.devDependencies['@sveltejs/package'] = '^2.0.0';
pkg.devDependencies['@sveltejs/package'] = '^2.1.0';
}

/** @type {Record<string, string>} */
Expand All @@ -112,12 +107,12 @@ export function update_pkg_json(config, pkg, files) {
// JSON.stringify will remove the undefined entries
pkg.exports[key] = {
types: has_type
? `./${out_dir}/${
? `./${
file.is_svelte ? `${file.dest}.d.ts` : file.dest.slice(0, -'.js'.length) + '.d.ts'
}`
: undefined,
svelte: needs_svelte_condition ? `./${out_dir}/${file.dest}` : undefined,
default: `./${out_dir}/${file.dest}`
svelte: needs_svelte_condition ? `./${file.dest}` : undefined,
default: `./${file.dest}`
};

if (Object.values(pkg.exports[key]).filter(Boolean).length === 1) {
Expand Down
34 changes: 16 additions & 18 deletions packages/migrate/migrations/package/migrate_pkg.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,29 +57,28 @@ test('Updates package.json', () => {
name: 'foo',
version: '1.0.0',
type: 'module',
files: ['package'],
scripts: {
packages: 'svelte-package -o package'
packages: 'svelte-package -o package -c'
},
exports: {
'./package.json': './package.json',
'.': {
types: './package/index.d.ts',
svelte: './package/index.js',
default: './package/index.js'
types: './index.d.ts',
svelte: './index.js',
default: './index.js'
},
'./foo/Bar.svelte': {
types: './package/foo/Bar.svelte.d.ts',
svelte: './package/foo/Bar.svelte',
default: './package/foo/Bar.svelte'
types: './foo/Bar.svelte.d.ts',
svelte: './foo/Bar.svelte',
default: './foo/Bar.svelte'
},
'./baz': {
types: './package/baz.d.ts',
default: './package/baz.js'
types: './baz.d.ts',
default: './baz.js'
},
'./ignored': './something.js'
},
svelte: './package/index.js'
svelte: './index.js'
});
});

Expand Down Expand Up @@ -118,20 +117,19 @@ test('Updates package.json #2', () => {
name: 'foo',
version: '1.0.0',
type: 'module',
files: ['dist'],
exports: {
'./package.json': './package.json',
'.': {
svelte: './dist/index.js',
default: './dist/index.js'
svelte: './index.js',
default: './index.js'
},
'./foo/Bar.svelte': {
svelte: './dist/foo/Bar.svelte',
default: './dist/foo/Bar.svelte'
svelte: './foo/Bar.svelte',
default: './foo/Bar.svelte'
},
'./baz': './dist/baz.js'
'./baz': './baz.js'
},
svelte: './dist/index.js'
svelte: './index.js'
});
});

Expand Down
6 changes: 6 additions & 0 deletions packages/package/src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ prog
.option('-i, --input', 'Input directory')
.option('-o, --output', 'Output directory', 'dist')
.option('-t, --types', 'Emit type declarations', true)
.option(
'-c, --copy',
'Copy package.json, readme, .npmignore and license into output folder',
false
)
.option('-w, --watch', 'Rerun when files change', false)
.action(async (args) => {
try {
Expand All @@ -43,6 +48,7 @@ prog
input: args.input ?? config.kit?.files?.lib ?? 'src/lib',
output: args.output,
types: args.types,
copy: args.copy,
config
};

Expand Down
27 changes: 27 additions & 0 deletions packages/package/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,33 @@ async function do_build(options, analyse_code) {
await process_file(input, output, file, options.config.preprocess, alias, analyse_code);
}

if (options.copy) {
const pkg = JSON.parse(fs.readFileSync(path.join(options.cwd, 'package.json'), 'utf-8'));
// See: https://pnpm.io/package_json#publishconfigdirectory
if (pkg.publishConfig?.directory || pkg.linkDirectory?.directory) {
delete pkg.publishConfig?.directory;
delete pkg.linkDirectory?.directory;
}
fs.writeFileSync(path.join(output, 'package.json'), JSON.stringify(pkg, null, 2));

for (const file of fs.readdirSync(options.cwd)) {
const lowercased = file.toLowerCase();
if (
!['README', 'LICENSE', '.npmignore'].some((name) =>
lowercased.startsWith(name.toLowerCase())
)
) {
continue;
}

const source = path.join(options.cwd, file);
if (fs.lstatSync(source).isDirectory()) continue;

const dest = path.join(options.output, file);
if (!fs.existsSync(dest)) fs.copyFileSync(source, dest);
}
}

console.log(
colors
.bold()
Expand Down
1 change: 1 addition & 0 deletions packages/package/src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export interface Options {
input: string;
output: string;
types: boolean;
copy: boolean;
config: {
extensions?: string[];
kit?: {
Expand Down
12 changes: 12 additions & 0 deletions packages/package/test/fixtures/copy-pkg-json/expected/Test.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<script>
import { createEventDispatcher } from 'svelte';
/**
* @type {string}
*/
export const astring = 'potato';

const dispatch = createEventDispatcher();
dispatch('event', true);
</script>

<slot {astring} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/** @typedef {typeof __propDef.props} TestProps */
/** @typedef {typeof __propDef.events} TestEvents */
/** @typedef {typeof __propDef.slots} TestSlots */
export default class Test extends SvelteComponentTyped<
{
astring?: string;
},
{
event: CustomEvent<any>;
} & {
[evt: string]: CustomEvent<any>;
},
{
default: {
astring: string;
};
}
> {
get astring(): string;
}
export type TestProps = typeof __propDef.props;
export type TestEvents = typeof __propDef.events;
export type TestSlots = typeof __propDef.slots;
import { SvelteComponentTyped } from 'svelte';
declare const __propDef: {
props: {
astring?: string;
};
events: {
event: CustomEvent<any>;
} & {
[evt: string]: CustomEvent<any>;
};
slots: {
default: {
astring: string;
};
};
};
export {};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as Test } from './Test.svelte';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as Test } from './Test.svelte';
14 changes: 14 additions & 0 deletions packages/package/test/fixtures/copy-pkg-json/expected/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "copy-pkg-json",
"private": true,
"version": "1.0.0",
"description": "test copy-pkg-json option",
"peerDependencies": {
"svelte": "^3.55.0"
},
"exports": {
".": {
"svelte": "./index.js"
}
}
}
1 change: 1 addition & 0 deletions packages/package/test/fixtures/copy-pkg-json/jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
14 changes: 14 additions & 0 deletions packages/package/test/fixtures/copy-pkg-json/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "copy-pkg-json",
"private": true,
"version": "1.0.0",
"description": "test copy-pkg-json option",
"peerDependencies": {
"svelte": "^3.55.0"
},
"exports": {
".": {
"svelte": "./index.js"
}
}
}
12 changes: 12 additions & 0 deletions packages/package/test/fixtures/copy-pkg-json/src/lib/Test.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<script>
import { createEventDispatcher } from 'svelte';
/**
* @type {string}
*/
export const astring = 'potato';

const dispatch = createEventDispatcher();
dispatch('event', true);
</script>

<slot {astring} />
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as Test } from './Test.svelte';
Empty file.
10 changes: 8 additions & 2 deletions packages/package/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ async function test_make_package(path, options) {
output,
types: true,
config,
copy: false,
...options
});

Expand Down Expand Up @@ -88,7 +89,7 @@ for (const dir of fs.readdirSync(join(__dirname, 'errors'))) {
const input = resolve(cwd, config.kit?.files?.lib ?? 'src/lib');

try {
await build({ cwd, input, output, types: true, config });
await build({ cwd, input, output, types: true, config, copy: false });
assert.unreachable('Must not pass build');
} catch (/** @type {any} */ error) {
assert.instance(error, Error);
Expand Down Expand Up @@ -138,6 +139,10 @@ test('create package and resolves $lib alias', async () => {
await test_make_package('resolve-alias');
});

test.only('create package and copy over package.json', async () => {
await test_make_package('copy-pkg-json', { copy: true });
});

test('SvelteKit interop', async () => {
await test_make_package('svelte-kit');
});
Expand All @@ -154,7 +159,8 @@ if (!process.env.CI) {
input: 'src/lib',
output: 'package',
types: true,
config
config,
copy: false
});

/** @param {string} file */
Expand Down