如何使用Webpack 2 Raw-Loader来读取文件

我目前被困在一个地方,我需要以HTTPS模式启动NodeJS服务器,并且需要读取cert文件,以便在https.createServer(options, app).listen(8443)命令中给出这些选项。 我很难理解如何将文件读入使用Webpack 2捆绑的TypeScript文件中。例如,

我有2个文件file.crt和file.key。 我想在创buildhttps服务器时开始读取这些文件,并开始监听给定的端口。 在常规TS / JS土地上我可以这样做:

“`

 import Config from '../env/config'; import Express from '../lib/express'; import * as https from 'https'; import * as fs from 'fs'; let config = new Config(); let app = Express.bootstrap().app; export default class AppService{ constructor(){ // console.log('blah:', fs.readFileSync('./file.txt')); } start(){ let options = { key: fs.readFileSync('file.key'), cert: fs.readFileSync('file.crt'), ca: fs.readFileSync('ca.crt'), passphrase: 'gulp' }; https.createServer(options, app).listen(config.port,()=>{ console.log('listening on port::', config.port ); }); } } 

但是,当webpack 2构build这些文件时,这些文件并没有被引入,所以当节点启动时无法find它们。 好吧,我明白了,但是我读过那个原始的加载程序会为此工作,所以我想我会试试看。

这是我的webpackconfiguration文件:

 // `CheckerPlugin` is optional. Use it if you want async error reporting. // We need this plugin to detect a `--watch` mode. It may be removed later // after https://github.com/webpack/webpack/issues/3460 will be resolved. const {CheckerPlugin} = require('awesome-typescript-loader'); const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin'); module.exports = { target: 'node', entry: './src/server.ts', output: { filename: 'dist/bundle.js' }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'] }, devtool: 'source-map', module: { rules: [ {test: /\.ts$/, use: 'awesome-typescript-loader'}, {test: /\.json$/, loader: 'json-loader'}, {test: /\.crt$/, use: 'raw-loader'} ] }, plugins: [ new CheckerPlugin() ], node: { global: true, crypto: 'empty', fs: 'empty', net: 'empty', process: true, module: false, clearImmediate: false, setImmediate: false } }; 

我认为,这意味着确定扫描项目,当你find任何与.crt文件,然后将它们与源地图捆绑为utf8string。 我所要做的就是import crtfile from 'file.crt'就像raw-loader doc的状态一样,但是import crtfile from 'file.crt'甚至不能编译现在的文件,说明它不能写入模块file.crt。 请帮助!! 我打了一堵墙。

但是,当webpack 2构build这些文件时,这些文件并没有被引入,所以当节点启动时无法find它们。

Webpack仅捆绑您导入的文件。 在你的情况下,你只是从文件系统读取,webpack不会触及这些function。 这并不意味着它在运行时不起作用,只需要在正在运行该包的目录中拥有要读取的文件,这些函数在包中没有不同的含义。

如果你想拥有这个包中的文件的内容,你确实可以使用raw-loader 。 首先import语句需要是一个相对path,否则它会查找一个模块。

 import crtfile from './file.crt'; 

与您的configuration,将在JavaScript中正常工作。 在TypeScript中,导入将是:

 import * as crtfile from './file.crt'; 

但是TypeScript对于导入不知道types的文件并不满意。 您可以通过在声明文件中定义types来解决该问题,例如custom.d.ts (如导入非代码资产所示 )。

 declare module "*.crt" { const content: any; export default content; }