如何使用Parcel从TypeScript文件导入非TypeScript资产

时间:2019-03-19 22:17:43

标签: javascript html css typescript parceljs

以下是Parcel文档的摘录:

  

您还可以从JavaScript文件导入非JavaScript资产,例如   CSS,HTML甚至图像文件。当您导入这些文件之一时,   它没有像其他一些捆绑程序那样内联。相反,它被放置在   一个单独的捆绑包(例如CSS文件)及其所有   依赖性。使用CSS模块时,将放置导出的类   在JavaScript套件中。其他资产类型将URL导出到输出   JavaScript包中的文件,以便您可以在代码中引用它们。

// Import a CSS file
import './test.css'

// Import a CSS file with CSS modules
import classNames from './test.css'

// Import the URL to an image file
import imageURL from './test.png'

// Import an HTML file
import('./some.html')
// or:
import html from './some.html'
// or:
require('./some.html')
     

如果要将文件内联而不是内联到JavaScript包中   通过URL引用它,您可以使用Node.js fs.readFileSync API来执行   那。该URL必须是静态可分析的,这意味着它不能具有   其中的任何变量(__dirname和__filename除外)。

import fs from 'fs'

// Read contents as a string
const string = fs.readFileSync(__dirname + '/test.txt', 'utf8')

// Read contents as a Buffer
const buffer = fs.readFileSync(__dirname + '/test.png')

// Convert Buffer contents to an image
;<img src={`data:image/png;base64,${buffer.toString('base64')}`} />

我尝试了其中一些操作,但是是从TypeScript文件中执行的,它似乎不起作用。

这是我要完成的工作的一个示例:

component.html

<h1>Some really big text</h1>
<p>Some much smaller text</p>

component.css

h1 {
  font-size: 80px;
  text-align: center;
}

p {
  font-size: 10px;
}

component.ts

import { styles } from './component.css;
import { html } from './component.html;

class Component extends HTMLElement {
  constructor() {
  super();

  // Append the styles and html to shadowRoot on element
}

customElements.define('app-root', Component);

这个想法是使用它们自己的单独的html,css和ts文件定义自定义元素。然后,根index.html文件可以指向main.ts文件,并且main.ts可以导入所有组件文件。我该如何工作?

0 个答案:

没有答案