我正在使用 Symfony 3.3 和 Assets 包。我的 config.yml 中有这个:
assetic:
debug: '%kernel.debug%'
use_controller: '%kernel.debug%'
filters:
cssrewrite: ~
typescript:
bin: "%kernel.root_dir%/../node_modules/typescript/bin/tsc"
apply_to: "\\.ts$"
当我尝试编译我的 TypeScript 文件时,出现此错误:
Output:
../../../../private/var/folders/94/45yn02792ksfglm12pjxxlp00000gn/T/assetic_typescript_in59bccf08e6357/my-form.ts.ts(6,1): error TS6131: Cannot compile modules using option 'out' unless the '--module' flag is 'amd' or 'system'.
../../../../private/var/folders/94/45yn02792ksfglm12pjxxlp00000gn/T/assetic_typescript_in59bccf08e6357/my-form.ts.ts(6,22): error TS2307: Cannot find module './my-obj.model'.
这发生在我使用像 import { Obj } from './my-obj.model';
这样的导入语句之后。如果我不使用 import 语句,ts 编译工作正常。
如何为 assetic 的 TypeScript 过滤器添加 --module system
参数或 tsconfig.json
?
最佳答案
error TS6131: Cannot compile modules using option 'out' unless the '--module' flag is 'amd' or 'system'.
目前无法通过 AsseticBundle
为 tsc
命令提供额外选项。
error TS2307: Cannot find module './model'.
这里的 AsseticBundle
将每个单独的 ts
文件保存到 tmp 目录/文件中进行编译,因此它也不支持此功能。
好消息是您可以覆盖 assetic.filter.typescript
服务的行为来修复它。让我们将这个类添加到应用程序中:
namespace AppBundle\Assetic\Filter;
use Assetic\Asset\AssetInterface;
use Assetic\Exception\FilterException;
use Assetic\Util\FilesystemUtils;
class TypeScriptFilter extends \Assetic\Filter\TypeScriptFilter
{
private $tscBin;
private $nodeBin;
public function __construct($tscBin = '/usr/bin/tsc', $nodeBin = null)
{
$this->tscBin = $tscBin;
$this->nodeBin = $nodeBin;
}
public function filterLoad(AssetInterface $asset)
{
$pb = $this->createProcessBuilder($this->nodeBin
? array($this->nodeBin, $this->tscBin)
: array($this->tscBin));
// using source path to compile and allow "imports".
$inputPath = $asset->getSourceRoot().DIRECTORY_SEPARATOR.$asset->getSourcePath();
$outputPath = FilesystemUtils::createTemporaryFile('typescript_out');
$pb
->add($inputPath)
// passing the required options here
->add('--module')->add('system')
->add('--out')
->add($outputPath)
;
$proc = $pb->getProcess();
$code = $proc->run();
if (0 !== $code) {
if (file_exists($outputPath)) {
unlink($outputPath);
}
throw FilterException::fromProcess($proc)->setInput($asset->getContent());
}
if (!file_exists($outputPath)) {
throw new \RuntimeException('Error creating output file.');
}
$compiledJs = file_get_contents($outputPath);
unlink($outputPath);
$asset->setContent($compiledJs);
}
}
然后,改变参数类的值来覆盖原来的服务:
# app/config/services.yml
parameters:
assetic.filter.typescript.class: 'AppBundle\Assetic\Filter\TypeScriptFilter'
您的 assetic
配置对我有用。
另一方面,为 Symfony 应用程序管理 Assets 的新推荐方式:Webpack Encore为您提供一个干净而强大的 API,用于捆绑 JavaScript 模块、预处理 CSS 和 JS 以及编译和缩小 Assets ,support for TypeScript装载机。
关于symfony - 如何为 assetic 的 TypeScript 过滤器指定 tsconfig.json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46251603/