1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Svelteのimport文で絶対パスを使えるようにする

Last updated at Posted at 2021-12-29

この記事の方法のほうがシンプルでよさそう(SvelteKit限定?)
※ ほとんどこちらの記事の意訳です。

やりたいこと

コンポーネントをimportするときのパス指定を、絶対パスで書きたい。

ありのままのSvelte

.svelte
import Component  from "../../../../components/Component.svelte";

(読み込みたいファイルと、読み込むファイルが離れれば離れるほど、パス指定が面倒になる。)

理想のSvelte

.svelte
import Component from "components/Component.svelte";

やりかた

@rollup/plugin-alias をインストールする

Terminal
npm install @rollup/plugin-alias --save-dev

rollup.config.jsで読み込む

rollup.config.jsは、Svelteプロジェクト作成時に自動的に生成されているハズ)

rollup.config.js
import alias from '@rollup/plugin-alias';

rollup.config.jsに絶対パスの定義(ルール)を書き込む

rollup.config.js
const aliases = alias({
  resolve: ['.svelte', '.js'], // どの拡張子のファイルでこのルールを有効にするか
  entries: [
    // find: 絶対パスの書き方 // replacement: その書き方で、どのフォルダを指すか
    // 以下は参考例です。
    { find: '', replacement: 'src/' },
    { find: 'components', replacement: 'src/components' },
  ]
});

rollup.config.jsexport defaultに追記する

export default自体はすでに書き込まれていて、
inputoutputpluginsなどの項目が既に存在しているハズ。

そのpluginsの配列の中に、さきほど定義したaliasesを追加してあげる。

rollup.config.js
export default {
  input: ...
  output: ...
  plugins: [
    aliases, //←これを追加する。
    //以下略

これで絶対パス指定ができるようになりました。
めでたしめでたし。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?